javascript - React Hooks 和组件生命周期等效项

标签 javascript reactjs react-hooks

使用诸如 useEffect 等 React 钩子(Hook)的 componentDidMountcomponentDidUpdatecomponentWillUnmount 生命周期钩子(Hook)的等效项是什么?

最佳答案

componentDidMount

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

function ComponentDidMount() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log('componentDidMount');
  }, []);

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

ReactDOM.render(
  <div>
    <ComponentDidMount />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

componentDidUpdate

componentDidUpdate() 在更新发生后立即调用。初始渲染不会调用此方法。 useEffect 在每个渲染上运行,包括第一个渲染。因此,如果您想要与 componentDidUpdate 严格等效,则必须使用 useRef 来确定组件是否已安装一次。如果您想更严格,请使用 useLayoutEffect(),但它会同步触发。在大多数情况下,useEffect() 应该足够了。

这个answer is inspired by Tholle ,所有功劳都归于他。

function ComponentDidUpdate() {
  const [count, setCount] = React.useState(0);

  const isFirstUpdate = React.useRef(true);
  React.useEffect(() => {
    if (isFirstUpdate.current) {
      isFirstUpdate.current = false;
      return;
    }

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

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

ReactDOM.render(
  <ComponentDidUpdate />,
  document.getElementById("app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

componentWillUnmount

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

function ComponentWillUnmount() {
  function ComponentWillUnmountInner(props) {
    React.useEffect(() => {
      return () => {
        console.log('componentWillUnmount');
      };
    }, []);

    return (
      <div>
        <p>componentWillUnmount</p>
      </div>
    );
  }
  
  const [count, setCount] = React.useState(0);

  return (
    <div>
      {count % 2 === 0 ? (
        <ComponentWillUnmountInner count={count} />
      ) : (
        <p>No component</p>
      )}
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <ComponentWillUnmount />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

关于javascript - React Hooks 和组件生命周期等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254017/

相关文章:

javascript - 删除存储有 'react-cookie' 的 cookie,无论域如何

javascript - 在 React 中重用不同状态的 Fetch (Flux)

javascript - react Hook : Stateless component VS Class component in the era of Hooks - which is better and recommended?

javascript - 错误意外标记}

php - 在 PHP 中为 Google Map 调用 JavaScript 函数

javascript - 如何删除 jquery 模态表单并将其保留为页面底部的简单 html 表单

javascript - 我的 useState 有问题吗?我觉得我的 Array ReactNative 中的值不正确

javascript - jquery 1.7.1 隐藏和显示无法正常工作

javascript - React,在包含相同组件的路由之间导航时处理获取的最佳方法

reactjs - 功能组件比类组件有更好的性能?