【问题标题】:How to detect a component will be updated with react hooks?如何检测组件将使用反应挂钩更新?
【发布时间】:2020-09-12 20:51:52
【问题描述】:

React hooks 提供了模仿生命周期方法 componentDidUpdateuseEffect 而没有依赖关系的可能性:

useEffect(() => {
   // componentDidUpdate
});

如何检测是否有一些 prop GOING 要用 react hooks 更新?

需要在某些更改之前执行一些代码。

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    只要组件重新渲染,就会调用没有依赖关系的 useEffect。这就像componentDidMountcomponentDidUpdate 的组合

    但是,如果您希望跟踪特定的道具更改,可以将其添加到 dependency array of useEffect

    useEffect(() => {
       // called on change of props.somename as well as initial render
    }, [props.somename]);
    

    还可以查看以下帖子,了解有关使用 useEffect 模拟生命周期方法以及仅在更新时执行 useEffect 的更多详细信息

    React hooks useEffect only on update?

    ReactJS lifecycle method inside a function Component

    附:您可以根据需要向依赖项数组添加多个值

    【讨论】:

      【解决方案2】:

      如果您试图模仿componentWillReceiveProps 的行为,您可以轻松地将您的逻辑放入组件的主体中:

      function MyComponent(props) {
        // do stuff with props (it's like componentWillReceiveProps)
        return (...);
      }
      

      你不需要钩子。

      请记住,useEffect 您的组件使用这些道具渲染后运行,而不是在之前运行。

      newProps -> MyComponent is called -> DOM updated -> useEffect called

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 2020-04-04
        • 2021-05-13
        • 2021-10-18
        • 2020-11-25
        • 2019-07-31
        • 1970-01-01
        • 2020-01-26
        • 2021-10-11
        相关资源
        最近更新 更多