我不太明白 React 中的“Mount”是什么意思以及何时触发 useEffect 和 clean up 函数。
在下面的例子中。看来 useToggle 钩子(Hook)“绑定(bind)”(正确的术语?)到 App 组件,并且每次变量 isOn
更新时,绑定(bind)的 App 组件都会重新渲染。但是,清理函数也会被调用。我尝试将其与 React 的类组件的生命周期进行比较。
如果我的理解有误,请纠正我。
引用:图表来自Trey Huffine进行编辑
生命周期中的useEffect(updateFunc => cleanupFunc, [dependency array])
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 。
useEffect
与 componentDidMount
有所不同,后者仅调用一次(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/