react改变props为什么shouldComponentUpdate触发了3次?

1.执行 componentDidMount 后执行了一个异步任务

2.异步任务完成后执行 setState

这里观察到 shouldComponentUpdate 执行了三次,(改变 props)

请问这是为什么呢?

什么时候什么原因触发的这三次shouldComponentUpdate呢?

伪代码:

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            source: require('../.....a.png'),
        };
    }

    componentDidMount() {
        this.init();
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log('shouldComponentUpdate');
        const needUpdate = JSON.stringify(nextProps) !== JSON.stringify(this.props) || nextState !== this.state;

        return needUpdate;
    }

    init = async () => {
        asyncFn().then((source) =>
            this.setState({
                source,
            })
        );
    };

    render() {
        return <Image 
            {...this.props} 
            source={this.state.source}/>;
    }
}
阅读 1.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题