【发布时间】:2019-03-21 16:55:41
【问题描述】:
我了解在 shouldComponentUpdate 中使用 nextProps 和 nextState 来根据 this.state.someProperty 与 nextState.someProperty 的比较结果来确定组件是否应该重新渲染。如果它们不同,则组件应重新渲染。
这很清楚。
但是,这似乎不是正在发生的事情。查看此代码。
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
this.counter =
this.counter.bind(this)
}
counter() {
setInterval(()=>{
this.setState({count: this.state.count+=1})
}, 10000);
}
componentDidMount() {
this.counter();
}
shouldComponentUpdate(nextProps, nextState) {
console.log(this.state.count + " " + nextState.count)
return true;
}
render() {
return (
<div>
<h1>This App Counts by the Second </h1>
<h1>{this.state.count}</h1>
</div>
);
}
};
在 shouldComponentUpdate 中,我记录了 state.count 和 nextState.count 值,它们每次都是等价的。他们不应该不同吗?如果不是,如果使用 setState 更改状态确保它们相同,那么检查它们是否等效的目的是什么?
【问题讨论】:
标签: javascript reactjs