使用像useEffect这样的React钩子的componentDidMountcomponentDidUpdatecomponentWillUnmount生命周期钩子的类似功能是什么?

推荐答案

组件安装

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

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

  return (
    <div>
      <p>组件安装: {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>

组件更新

更新发生后立即调用组件更新().初始渲染时不调用此方法.useEffect在每个渲染上运行,包括第一个渲染.因此,如果你想有一个严格的类似功能组件更新,你必须使用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('组件更新');
  });

  return (
    <div>
      <p>组件更新: {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>

组件将卸载

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

function ComponentWillUnmount() {
  function ComponentWillUnmountInner(props) {
    React.useEffect(() => {
      return () => {
        console.log('组件将卸载');
      };
    }, []);

    return (
      <div>
        <p>组件将卸载</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>

Reactjs相关问答推荐

从另一个组件更改组件中const的状态

如何使用next.js以DOM为目标在映射中使用Ref

为什么Next.js 14无法解析页面路由路径?

FireBase Reaction Native-在呈现视图之前等待响应

Reaction路由DOM v6不包含上下文(Supabase)

使用自动播放的视频组件呈现登录页面时出现JEST测试错误

在 Next13 中将 props 传递给 onClick 从服务器到客户端组件

计数器递增 2 而不是 1

如何在不使用 Axios 的情况下将图像文件从 React.js 发送到 Spring Boot Rest API?

使用 MuiCssBaseline 在所有 MUI v5 标签上设置边距 0

React 测试库 - 如何断言异步函数之间的中间状态?

为嵌套路由配置一个不存在的 url 的重定向

基于标记名的博客详细信息分组没有发生

Material UI v5.11 - Prop sx 在响应式中写了两次

我刚刚部署了我的 Vite React 站点,但我的图标/图像没有部署

在 redux 中分派到另一个减少时状态值不会改变

谁能根据经验提供有关 useEffect 挂钩的更多信息

当我在其中传递 2 个箭头函数时,为什么我的 onClick 事件不适用于 useState

ClearInterval 在 React 中的 useRef 没有按预期工作

Cypress 中的 process.env 空对象