考虑下面的钩子示例
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>
}
}
但是我的问题是如何强制上面的功能组件立即用钩子重新渲染?
原文由 Hemadri Dasari 发布,翻译遵循 CC BY-SA 4.0 许可协议
这可以通过
useState
或useReducer
,因为useState
在内部使用useReducer
:forceUpdate
不打算在正常情况下使用,仅用于测试或其他未解决的情况。这种情况可以以更传统的方式解决。setCount
是不当使用forceUpdate
的一个示例,setState
出于性能原因是异步的,不应仅仅因为状态更新未正确执行而强制同步。如果一个状态依赖于先前设置的状态,这应该使用 更新函数 来完成,setCount
可能不是一个说明性示例,因为它的目的尚不清楚,但更新程序函数就是这种情况:这被 1:1 转换为钩子,但用作回调的函数应该更好地被记忆: