小编典典

如何在React中强制使用挂钩重新渲染组件?

reactjs

考虑下面的钩子示例

   import { useState } from 'react';

   function Example() {
       const [count, setCount] = useState(0);

       return (
           <div>
               <p>You clicked {count} times</p>
               <button onClick={() => setCount(count + 1)}>
                  Click me
               </button>
          </div>
        );
     }

基本上,我们使用this.forceUpdate()方法强制组件在React类组件中立即重新呈现,如以下示例所示

    class Test extends Component{
        constructor(props){
             super(props);
             this.state = {
                 count:0,
                 count2: 100
             }
             this.setCount = this.setCount.bind(this);//how can I do this with hooks in functional component 
        }
        setCount(){
              let count = this.state.count;
                   count = count+1;
              let count2 = this.state.count2;
                   count2 = count2+1;
              this.setState({count});
              this.forceUpdate();
              //before below setState the component will re-render immediately when this.forceUpdate() is called
              this.setState({count2: count
        }

        render(){
              return (<div>
                   <span>Count: {this.state.count}></span>. 
                   <button onClick={this.setCount}></button>
                 </div>
        }
 }

但是我的查询是如何强制上述功能组件立即使用挂钩重新渲染?


阅读 615

收藏
2020-07-22

共1个答案

小编典典

可以使用useState或进行useReducer,因为在内部useState使用useReducer

const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);

forceUpdate不打算在正常情况下使用,仅在测试或其他出色情况下使用。可以以更常规的方式解决这种情况。

setCount是使用不当的例子forceUpdatesetState是异步的性能,而且不应该被强迫只是因为状态更新没有正确执行是同步的。如果状态依赖于先前设置的状态,则应使用updater函数来完成,

如果需要基于先前的状态来设置状态,请阅读以下有关updater参数的信息。

<…>

更新器功能接收到的状态和道具都保证是最新的。更新器的输出与state合并在一起。

setCount 可能不是说明性的示例,因为其用途尚不清楚,但updater函数就是这种情况:

setCount(){
  this.setState(({count}) => ({ count: count + 1 }));
  this.setState(({count2}) => ({ count2: count + 1 }));
  this.setState(({count}) => ({ count2: count + 1 }));
}
2020-07-22