【发布时间】:2019-04-12 09:46:01
【问题描述】:
考虑下面的钩子示例
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>
}
}
但我的问题是如何强制上面的功能组件立即使用钩子重新渲染?
【问题讨论】:
-
您能否发布使用
this.forceUpdate()的原始组件版本?也许有一种方法可以在没有它的情况下完成同样的事情。 -
setCount 中的最后一行被截断。目前尚不清楚 setCount 在当前状态下的目的是什么。
-
这只是this.forceUpdate()之后的一个动作;我补充说只是为了在我的问题中解释 this.forceUpdate()
-
为了它的价值:我正在为此苦苦挣扎,因为我认为我需要手动重新渲染,最后意识到我只需将外部持有的变量移动到状态挂钩并利用设置功能,无需重新渲染即可解决我的所有问题。并不是说它从不需要,但值得第三次和第四次查看它是否在您的特定用例中实际上需要。
标签: javascript reactjs react-native react-hooks