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