如何在React中使用钩子生命周期方法? [英] How to use lifecycle methods with hooks in React?

查看:116
本文介绍了如何在React中使用钩子生命周期方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过了反应v16.7.0中介绍的钩子。

I have gone through hooks introduced in react v16.7.0.

https://reactjs.org/ docs / hooks-intro.html

所以我对钩子的理解是我们可以在功能组件中使用状态,而无需在反应中编写类组件。这真是一个非常了不起的功能。

So my understanding about hooks is we can play with state in functional component without writing class components in react. This is really amazing feature.

但是我没有清楚地了解在功能组件中使用钩子。

But I am not getting clear picture about using hooks in functional components.

   import { useState } from 'react';

   function Example() {
   const [count, setCount] = useState(0);

    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
         Click me
        </button>
      </div>
   );
  }

如果我使用钩子,如何在上面的功能组件中使用生命周期方法?

how can I use life cycle methods in the above functional component if I use hooks?

推荐答案

以下是最常见生命周期的示例:

Here are examples for the most common lifecycles:

将一个空数组作为第二个参数传递给 useEffect()仅在mount上运行回调。

Pass an empty array as the second argument to useEffect() to run only the callback on mount only.

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, []); // Pass an empty array to run only callback on mount only.

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}



componentDidUpdate (松散) )



通过将单个参数传递到 useEffect ,它将在每次渲染后运行。这是一个松散的等价物,因为这里有一点点差别 componentDidUpdate 在第一次渲染后不会运行,但是这个钩子版本在每次渲染后运行。

componentDidUpdate (loose)

By passing just the single argument into useEffect, it will run after every render. This is a loose equivalent because there's a slight difference here being componentDidUpdate will not run after the first render but this hooks version runs after every render.

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }); // No second argument, so run after every render.

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}



componentDidUpdate (严格)



此示例与上述示例的区别在于此处的回调不会在初始渲染时运行,严格模仿 componentDidUpdate <的语义/ code>。这个答案是由Tholle提供的,所有功劳归于他。

componentDidUpdate (strict)

The difference of this example with the example above is that the callback here would not run on initial render, strictly emulating the semantics of componentDidUpdate. This answer is by Tholle, all credit goes to him.

function Example() {
  const [count, setCount] = useState(0);

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log('componentDidUpdate');
  });

  return (
    <div>
      <p>componentDidUpdate: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}



componentWillUnmount



useEffect 的回调参数中返回一个回调函数,它将在卸载前调用。

componentWillUnmount

Return a callback in useEffect's callback argument and it will be called before unmounting.

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // Return a callback in useEffect and it will be called before unmounting.
    return () => {
      console.log('componentWillUnmount!');
    };
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}



shouldComponentUpdate



您可以使用 React.PureComponent React.memo <在组件级别实现此目的/ code>。为防止重新呈现子组件,此示例取自反应文档

function Parent({ a, b }) {
  // Only re-rendered if `a` changes:
  const child1 = useMemo(() => <Child1 a={a} />, [a]);
  // Only re-rendered if `b` changes:
  const child2 = useMemo(() => <Child2 b={b} />, [b]);
  return (
    <>
      {child1}
      {child2}
    </>
  )
}



getDerivedStateFromProps



再次,取自 React docs

function ScrollView({row}) {
  let [isScrollingDown, setIsScrollingDown] = useState(false);
  let [prevRow, setPrevRow] = useState(null);

  if (row !== prevRow) {
    // Row changed since last render. Update isScrollingDown.
    setIsScrollingDown(prevRow !== null && row > prevRow);
    setPrevRow(row);
  }

  return `Scrolling down: ${isScrollingDown}`;
}



getSnapshotBeforeUpdate



还没有挂钩的等价物。

getSnapshotBeforeUpdate

No equivalent for hooks yet.

还没有挂钩的等价物。

这篇关于如何在React中使用钩子生命周期方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆