大家都知道生命周期shouldComponentUpdate返回false时,不会进行后续的渲染,那这个时候state是什么情况呢。我们看一下demo
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {number: 1};
// 这边绑定是必要的,这样 `this` 才能在回调函数中使用
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
number: this.state.number + 1
}));
}
shouldComponentUpdate(nextProps, nextState) {
if(this.state.number == 4) {
return false
}
return true
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.number}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('example')
);
number是4的时候,我们返回false。运行结果表明,当按钮的数字是4的时候,再点击,数字不变化,接着点击,数字由4变成了6。表明,shouldComponentUpdate返回false不会影响state的改变,只是不接着进行渲染了而已。
接下来,应该把生命周期里每个阶段里调用setState会有什么后果,深入搞明白,深入React技术栈30页,还有更多的书籍先看一看。
转载于:https://www.cnblogs.com/zhansu/p/10294496.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)