[英]React 'useEffect' hook replaces how many lifecycle methods?
How many lifecycle methods can be replaced by React useEffect
? React useEffect
可以替代多少生命周期方法?
I found an article on the useEffect
hook that claims that it can replace only three, ie componentDidMount
, componentDidUpdate
and componentWillUnmount
.我发现一篇关于useEffect
hook 的文章声称它只能替换三个,即componentDidMount
、 componentDidUpdate
和componentWillUnmount
。
What about others?其他人呢?
That is actually all.这实际上就是全部。 useEffect() is called once component is mounted and than on every state update. useEffect() 在组件安装后调用,而不是在每次状态更新时调用。 If you want to use it as componentWillUnmout you have to return a cleanup function like so如果你想把它用作 componentWillUnmout 你必须像这样返回一个清理函数
useEffect(() => {
//something you want to do
return () => console.log('cleanup is running');
});
Nope that's pretty much it, though it comes close to componentWillUpdate
when you return a function and dont pass dependencies (it just doesn't run before the first render)不,差不多就是这样,尽管当您返回一个函数并且不传递依赖项时它接近componentWillUpdate
(它只是在第一次渲染之前不运行)
It's a really simple hook when you think about.仔细想想,这是一个非常简单的钩子。 The rules are pretty straightforward:规则非常简单:
The function you pass to useEffect
:您传递给useEffect
的函数:
The function your return from your useEffect
function:您从useEffect
函数返回的函数:
It's probably best not to think about lifecycle events it replaces.最好不要考虑它取代的生命周期事件。 Instead think about these 4 rules and how get them to run your functions when you want.而是考虑这 4 条规则以及如何让它们在您需要时运行您的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.