`React.PureComponent` 导致组件不更新

写轮播图组件的时候,React.PureComponent 莫名其妙的导致state修改后,而组件不更新,改成Component就ok了

如下:定时器每秒执行一次,但是ui不更新,控制台显示定时执行4次后(长度是4),才会render1次

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>;
    }
}

clipboard.png

阅读 3.9k
2 个回答

React.PureComponent  其实是重写了SCU(shouldComponentUpdate)方法。

React.Component shouldComponentUpdate 的实现是直接返回true。

这就是两者的区别。 造成这样的情况的原因就在于shouldComponentUpdate”错误“地将返回值变成false了。

PureComponent 重写的SCU其实就是shallow equal 两个state和nextState,prop和nextProps。

从你的代码中看,是

let nextIndex=++preState.index; 
// 等价于

let nextIndex = preState = preState.index + 1;

因此不仅仅修改了nextIndex, 同时也修改了preState.index.

你可以继承React.Component,自己写SCU,然后debug看一下就明白了。

希望我的回答对你有帮助。

 let nextIndex=++preState.index; // 改变了 preState 的值, 导致当前状态和之前状态的 index 值相同, 所以 PureComponent 在 shouldComponentUpdate 会返回 false.

改为

 let nextIndex= preState.index + 1;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题