reactjs - 在组件生命周期中,React 的 useEffect 何时被触发?

标签 reactjs

我不太明白 React 中的“Mount”是什么意思以及何时触发 useEffect 和 clean up 函数。

在下面的例子中。看来 useToggle 钩子(Hook)“绑定(bind)”(正确的术语?)到 App 组件,并且每次变量 isOn 更新时,绑定(bind)的 App 组件都会重新渲染。但是,清理函数也会被调用。我尝试将其与 React 的类组件的生命周期进行比较。

如果我的理解有误,请纠正我。

引用:图表来自Trey Huffine进行编辑

生命周期中的

useEffect(updateFunc => cleanupFunc, [dependency array]) enter image description here

const { useReducer, useEffect } = React;

// Purposefully moved the toggle logic to a custom hook for understanding
function useToggle(inital) {
  const [isOn, toggle] = useReducer(isOn => !isOn, inital);
  useEffect(()=>{
    console.log("update function called");
    return () => console.log("cleanup function called");
  }, [isOn])
  return [isOn, toggle];
}

function App() {
  const [isOn, toggle] = useToggle(false);
  return (
    <div>
      <input type='checkbox' value={isOn} onClick={toggle}/> 
      Click Me
    </div>
  )
}

ReactDOM.render(<App/>, document.querySelector('.App'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div class='App'/>

最佳答案

安装是指组件刚刚添加到 DOM 中。在类组件中,它是调用构造函数之后的下一个调用之一。

在功能组件中,我们实际上没有 onMount 事件,而是有 useEffect Hook 。

useEffectcomponentDidMount 有所不同,后者仅调用一次(onMount),而前者每次重新渲染组件时都会调用。每当状态/属性发生变化时,组件就会重新渲染。

来自 React 文档:

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

由于 useEffect 可以被多次调用,因此它也必须多次清理:

When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.

关于reactjs - 在组件生命周期中,React 的 useEffect 何时被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64384256/

相关文章:

javascript - 使用 React 监听整个 dom 上的点击事件的正确方法是什么?

javascript - 使用 ref 输入 React 组件? typescript

javascript - TypeError : func. apply 不是函数

javascript - 从 ReactJS 中导入的函数更改类状态

javascript - 来自前端的 Linkedin oauth/v2/accessToken API 的 CORS 错误

javascript - 将 css transition 应用于元素的宽度,使其覆盖其容器 div [ReactJS] 的 100% 宽度

reactjs - 使用 header 配方的 Apollo 授权不起作用

javascript - 使用 webpack 和 React 构建的工作流程。当我运行 'npm run dev' 时,出现错误 :Module parse failed

javascript - 删除链式 promise

javascript - 如何从响应中读取文件名-reactJs