在 Props 改变后执行一个函数

Nee*_*uza 2 javascript reactjs react-redux react-lifecycle react-lifecycle-hooks

我想在父组件中更改道具后在子组件中执行一个函数,而不必管理子/父中的额外状态。

<ParentCompoenent 
  myCallback={() => {}}
  myList={['a','b','c']}
/>
Run Code Online (Sandbox Code Playgroud)

子组件.js

componentWillReceiveProps(nextProps) {
  console.log(this.props.myList, '==', nextProps.myList);  // Outputs ['a','b','c'] == ['a','b','c']
}
Run Code Online (Sandbox Code Playgroud)

当我试图控制 componentWillReceiveProps 中的 nextProps 时,即使在更改道具后,它每次都会给出相同的结果。

小智 5

您必须componentDidUpdate在类组件和useEffect函数组件中使用...

componentDidUpdate 像这样:

    componentDidUpdate(prevProps, prevState) {
            if (prevProps.something !== this.props.something) {
                   console.log('something prop has changed.')
            }
    }
Run Code Online (Sandbox Code Playgroud)

componentDidUpdate将运行console.log每一个新的道具是从不同的时间prevProps

并且useEffect您只需将道具添加到其依赖项中:

useEffect(()=>{
    console.log('something prop has changed.')
},[props.something]);
Run Code Online (Sandbox Code Playgroud)

useEffect 每次该道具的值发生变化时都会调用该函数。


HMR*_*HMR 1

不确定您的问题与 React Redux 有什么关系,但这是您的代码,没有显示您所描述的行为(您在问题中发布的代码没有任何问题)。请提供您的问题的最小可重现示例。

class ChildComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    console.log(this.props.myList, '==', nextProps.myList); // Outputs ['a','b','c'] == ['a','b','c']
  }
  render() {
    return (
      <pre>
        {JSON.stringify(this.props.myList, undefined, 2)}
      </pre>
    );
  }
}
const ParentCompoenent = () => {
  const [myList, setMyList] = React.useState([1, 2, 3]);
  const changeList = React.useCallback(
    () => setMyList((list) => list.concat(list.length + 1)),
    []
  );
  return (
    <div>
      <button onClick={changeList}>Change list</button>
      <ChildComponent myList={myList} />
    </div>
  );
};

ReactDOM.render(
  <ParentCompoenent />,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)

您应该避免使用 componentWillReceiveProps,也许使组件成为功能组件并使用useEffect挂钩或使用did mount、did update 以及可能将卸载类组件。