【问题标题】:Execute a function after Props changeProps 改变后执行一个函数
【发布时间】:2021-05-11 19:38:28
【问题描述】:

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

<ParentCompoenent 
  myCallback={() => {}}
  myList={['a','b','c']}
/>

ChildComponent.js

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

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

【问题讨论】:

    标签: javascript reactjs react-redux react-lifecycle react-lifecycle-hooks


    【解决方案1】:

    你必须在类组件中使用componentDidUpdate,在函数组件中使用useEffect...

    componentDidUpdate 像这样:

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

    componentDidUpdate 将在每次新道具与prevProps 不同时运行console.log

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

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

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

    【讨论】:

    【解决方案2】:

    不确定您的问题与 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')
    );
    <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>

    您应该使用 componentWillReceiveProps avoid 并可能使组件成为功能组件并使用 useEffect 钩子或将 did mount, did update and possibly will unmount 用于类组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      相关资源
      最近更新 更多