如何在 React 中使用带钩子的生命周期方法?

新手上路,请多包涵

我已经了解了 react v16.7.0 中引入的钩子。

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

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

但是我不清楚在功能组件中使用钩子。

    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>
   );
  }

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

原文由 Hemadri Dasari 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
2 个回答

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

componentDidMount

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

 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 不会在第一次渲染后运行,但这个挂钩版本在每次渲染后运行。

 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 的语义。这个 答案是由 Tholle 提供的,所有功劳都归功于他。

 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 的回调参数中返回回调,它将在卸载前调用。

 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.PureComponentReact.memo 在组件级别实现此目的。为了防止重新渲染子组件,此示例取自 React 文档

 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 文档

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

还没有钩子的等价物。

componentDidCatch

还没有钩子的等价物。

原文由 Yangshun Tay 发布,翻译遵循 CC BY-SA 4.0 许可协议

React 团队为此提供了一个 useEffect 钩子。让我们以您的示例中的组件为计数添加服务器上传,否则我们将把它放在例如 componentDidUpdate 中:

  import { useState, useEffect } from 'react';

 function Example() {
   const [count, setCount] = useState(0);
   useEffect(() => {
     fetch(
       'server/url',
       {
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'
         },
         body: JSON.stringify({count}),
       }
     );
   });

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

在此示例中,这似乎不是一个巨大的胜利,因为它不是。但是生命周期方法的问题是您只能在组件中获得其中的每一个。如果你想上传到服务器、触发事件、将消息放入队列,而这些事情都不相关怎么办?太糟糕了,它们都挤在了 componentDidUpdate 中。或者你有 n 包装的 HOC 层 n 你想做的事情。但是使用钩子,您可以将所有这些拆分为对 useEffect 的解耦调用,而无需不必要的 HOC 层。

原文由 Jared Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题