考虑以下Hooks示例
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() 方法来强制立即重新渲染组件。
Translated:In class components, we can use the `this.forceUpdate()` method to force the component to be re-rendered immediately.
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>
}
}
但我的问题是如何使用钩子立即强制上述功能组件进行重新渲染?
this.forceUpdate()
的原始组件版本吗?也许有一种方法可以在不使用它的情况下实现相同的效果。 - Jacob