react 生命挂钩_使用React挂钩而不是生命周期方法

react 生命挂钩

How to replace React lifecycle methods with React Hooks in functional components? First, let’s see to lifecycle methods diagram.

如何在功能组件中用React Hooks替换React生命周期方法? 首先,让我们看一下生命周期方法图 。

You don’t need the constructor method in functional components. Use the useState Hook to initialize the state.

在功能组件中不需要constructor方法。 使用useState Hook初始化状态。

The common React component lifecycle methods are componentDidMount, componentDidUpdate and componentWillUnmount. For all cases we should use the useEffectHook. Let’s see an example for details.

常见的React组件生命周期方法是 componentDidMount, componentDidUpdatecomponentWillUnmount. 对于所有情况,我们都应该使用useEffect Hook 。 让我们看一个示例以了解详细信息。

//componentDidMount and componentDidUpdate. An effect re-runs every render


useEffect(() => {
    // to do smth...
})
  
//componentDidMount. An effect runs only on mount


useEffect(() => {
    // to do smth...
}, [])

For componentWillUnmount method, we should add the return statement to the useEffect Hook.

对于componentWillUnmount方法,我们应该将return语句添加到useEffect Hook中。

useEffect(() => {
  // to do smth...


  return () => {
    // to do smth else when a component is unmounted...
  }
})

To improve the performance of application we use a condition, an effect re-runs only if props or state were changed. It also works for an effect with the return statement. Have a look:

为了提高应用程序的性能,我们使用一个条件,只有在更改道具或状态时,效果才会重新运行。 它也可以与return语句一起起作用。 看一看:

useEffect(() => {
  console.log(title)
}, [title]) // Re-run the effect only if title was changed

Let's move on. Instead of theshouldComponentUpdate method we can use theReact.memo HOC for the same goal. It’s like the React.PureComponent, but for function components.

让我们继续。 可以使用React.memo HOC代替shouldComponentUpdate方法来实现相同的目标。 就像React.PureComponent ,但是对于功能组件。

const Component = React.memo(function Component(props) {
 // your code is here...
})

The method getDerivedStateFromProps is really uncommon and React docs advise to schedule an update while rendering instead.

方法getDerivedStateFromProps确实不常见,React docs建议在渲染时安排更新。

For methods getSnapshotBeforeUpdate, getDerivedStateFromError and componentDidCatch there are no Hook equivalents yet.

对于方法getSnapshotBeforeUpdategetDerivedStateFromErrorcomponentDidCatch ,还没有等效的Hook。

翻译自: https://medium.com/weekly-webtips/using-react-hooks-instead-of-lifecycle-methods-301216a3b435

react 生命挂钩

你可能感兴趣的:(react)