【问题标题】:Does useEffect determine whether component rerendring?useEffect 是否确定组件是否重新渲染?
【发布时间】:2020-10-21 11:10:08
【问题描述】:

现在我正在将基于类的组件迁移到功能组件中。据我所知,生命周期方法 componentDidUpdate , componentWillUnmount,componentDidMount 可以替换为 useEffect 钩子。

useEffect hooks 是否与shouldComponentUpdate 无关,无法判断组件是否重新渲染?

【问题讨论】:

标签: reactjs


【解决方案1】:

一般来说,useEffect 在状态对象更新时运行,它与重新渲染是分开的。 docs 是相当不错的顺便说一句。

【讨论】:

    【解决方案2】:

    useEffect 基于其依赖数组的变化运行。可以用作componentDidMount

    // empty [] dependency array -> use effect runs once after mount
    useEffect(() => {}, [])
    

    对于shouldComponentUpdate ,请看这里:https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate

    您可以为此使用 React.memo:

    const Button = React.memo((props) => {
      // your component
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2021-05-08
      • 2022-08-21
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多