18

我已经浏览了 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>
   );
  }

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

4

4 回答 4

61

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

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.PureComponent或在组件级别上实现此目的React.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

还没有钩子的等价物。

于 2018-11-11T22:10:31.143 回答
2

好吧,您实际上并没有生命周期方法。=) 但是您可以使用此处所示的效果挂钩https://reactjs.org/docs/hooks-effect.html

效果挂钩将能够复制 componentDidMount、componentDidUpdate 和 componentWillUnmount 的行为

所以你真的不需要组件中的生命周期方法。效果挂钩正在取代它们。=)

阅读上面的链接,您将获得一些关于它们如何工作的示例。

于 2018-11-08T19:16:11.543 回答
2

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 层。

于 2018-11-08T19:19:39.680 回答
1

功能组件是纯粹的无状态组件。但是在 React 16.8 中,他们添加了 Hooks。钩子可以用来代替状态和生命周期方法。

是的,你可以把useEffect Hook 想成 Like

  • 组件DidMount

  • 组件DidUpdate ,

  • 组件WillUnmount

  • shouldComponentUpdate结合起来。

  • 注意它是componentDidMountcomponentDidUpdatecomponentWillUnmount 和 shouldComponentUpdate的紧密替代品

于 2020-06-30T15:23:30.723 回答