在Props改变后执行一个函数
我想在父组件中更改道具后在子组件中执行一个函数,而不必管理子/父中的额外状态。
<ParentCompoenent
myCallback={() => {}}
myList={['a','b','c']}
/>
子组件.js
componentWillReceiveProps(nextProps) {
console.log(this.props.myList, '==', nextProps.myList); // Outputs ['a','b','c'] == ['a','b','c']
}
当我试图控制 componentWillReceiveProps 中的 nextProps 时,即使在更改道具后,它每次都会给出相同的结果。
回答
您必须componentDidUpdate在类组件和useEffect函数组件中使用...
componentDidUpdate 像这样:
componentDidUpdate(prevProps, prevState) {
if (prevProps.something !== this.props.something) {
console.log('something prop has changed.')
}
}
componentDidUpdate将运行console.log每一个新的道具是从不同的时间prevProps。
并且useEffect您只需将道具添加到其依赖项中:
useEffect(()=>{
console.log('something prop has changed.')
},[props.something]);
useEffect 每次该道具的值发生变化时都会调用该函数。