写轮播图组件的时候,React.PureComponent
莫名其妙的导致state修改后,而组件不更新,改成Component
就ok了
如下:定时器每秒执行一次,但是ui不更新,控制台显示定时执行4次后(长度是4),才会render
1次
class CyclePic extends React.PureComponent{
constructor(props){
super(props);
this.togglePic=this.togglePic.bind(this);
this.stopToggle=this.stopToggle.bind(this);
this.timer;
this.state={
index:0
}
}
componentDidMount(){
this.togglePic();
}
componentWillUnMount(){
this.stopToggle();
}
togglePic(){
this.timer=setInterval(()=>{
console.log(111)
this.setState((preState,currentProps)=>{
let nextIndex=++preState.index;
if(nextIndex>currentProps.pics.length-1){
nextIndex=0;
}
return {index:nextIndex}
});
},1000);
}
stopToggle(){
clearInterval(this.timer);
}
render(){
console.log(222);
return <div>{this.state.index}</div>;
}
}
React.PureComponent 其实是重写了SCU(shouldComponentUpdate)方法。
React.Component shouldComponentUpdate 的实现是直接返回true。
这就是两者的区别。 造成这样的情况的原因就在于shouldComponentUpdate”错误“地将返回值变成false了。
PureComponent 重写的SCU其实就是shallow equal 两个state和nextState,prop和nextProps。
从你的代码中看,是
因此不仅仅修改了nextIndex, 同时也修改了preState.index.
你可以继承React.Component,自己写SCU,然后debug看一下就明白了。
希望我的回答对你有帮助。