我对 react 16 的新生命周期感到困惑,getDerivedStateFromProps 用例。以下面的代码为例,根本不需要 getDerivedStateFromProps,因为我可以通过 componentDidUpdate 实现我想要的。
export class ComponentName extends Component {
//what is this for?
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.filtered !== prevState.filtered && nextProps.filtered === 'updated') {
return {
updated: true //set state updated to true, can't do anything more?
};
}
return null;
}
componentDidUpdate(prevProps, prevState) {
if(prevProps.filtered !== this.state.filtered && this.state.filtered === 'updated'){
console.log('do something like fetch api call, redirect, etc..')
}
}
render() {
return (
<div></div>
);
}
}