简体   繁体   English

React 'useEffect' hook 替换了多少生命周期方法?

[英]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 的文章声称它只能替换三个,即componentDidMountcomponentDidUpdatecomponentWillUnmount

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的函数:

  • runs after every render, unless you provide a dependency array.每次渲染后运行,除非您提供依赖数组。
  • If you provide in a dependency array, it runs on first render, and then whenever the dependencies change.如果您在依赖项数组中提供,它会在第一次渲染时运行,然后在依赖项发生变化时运行。

The function your return from your useEffect function:您从useEffect函数返回的函数:

  • Is run before each render (except the very first) unless you provide a dependency array.除非您提供依赖项数组,否则在每次渲染之前运行(除了第一次渲染)。
  • If you provide a dependency array, it is run before a render where the dependencies have changed, or the component unmounts.如果您提供依赖项数组,则它会在依赖项已更改或组件卸载的渲染之前运行。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM