考虑下面的钩子示例
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> } }
但是我的查询是如何强制上述功能组件立即使用挂钩重新渲染?
可以使用useState或进行useReducer,因为在内部useState使用useReducer:
useState
useReducer
const [, updateState] = React.useState(); const forceUpdate = React.useCallback(() => updateState({}), []);
forceUpdate不打算在正常情况下使用,仅在测试或其他出色情况下使用。可以以更常规的方式解决这种情况。
forceUpdate
setCount是使用不当的例子forceUpdate,setState是异步的性能,而且不应该被强迫只是因为状态更新没有正确执行是同步的。如果状态依赖于先前设置的状态,则应使用updater函数来完成,
setCount
setState
如果需要基于先前的状态来设置状态,请阅读以下有关updater参数的信息。 <…> 更新器功能接收到的状态和道具都保证是最新的。更新器的输出与state合并在一起。
如果需要基于先前的状态来设置状态,请阅读以下有关updater参数的信息。
<…>
更新器功能接收到的状态和道具都保证是最新的。更新器的输出与state合并在一起。
setCount 可能不是说明性的示例,因为其用途尚不清楚,但updater函数就是这种情况:
setCount(){ this.setState(({count}) => ({ count: count + 1 })); this.setState(({count2}) => ({ count2: count + 1 })); this.setState(({count}) => ({ count2: count + 1 })); }