【问题标题】:want to know why componentWillUnmount execute when a component update想知道为什么组件更新时会执行componentWillUnmount
【发布时间】:2021-01-28 17:04:07
【问题描述】:

App.js

import React from "react";
import CounterOne from "./CounterOne";
function App() {
  const [display, setDisplay] = React.useState(true);
  return (
    <>
      {display && <CounterOne />}
      <button
        onClick={() => {
          setDisplay(!display);
        }}
      >
        display
      </button>
    </>
  );
}

export default App;

CounterOne.js

import React, { useState } from "react";

function CounterOne() {
  const [count, setCount] = useState(0);
  React.useEffect(() => {
    console.log("component did update");
    return () => {
      console.log("component will unmount");
    };
  }, [count]);

  return (
    <div>
      <p>Count is {count}</p>
      <button
        onClick={() => {
          setCount(0);
        }}
      >
        reset
      </button>
      <button
        onClick={() => {
          setCount(count + 5);
        }}
      >
        Add 5
      </button>
      <button
        onClick={() => {
          setCount(count - 1);
        }}
      >
        Sub 1
      </button>
    </div>
  );
}

export default CounterOne;

当我点击 Add 5 或 sub 1 按钮时,组件会重新渲染,然后在浏览器控制台中打印

组件将卸载

组件确实更新了

我很困惑为什么在状态更新发生时会执行卸载部分

【问题讨论】:

标签: reactjs use-effect


【解决方案1】:

因为当你改变一个组件的状态时,React 会重新渲染整个组件。所以会先卸载旧组件,触发useEffect中的return回调。当一个新组件被挂载时,useEffect 内部的逻辑将再次被触发,因此在“组件将卸载”消息之后您会看到“组件确实更新”。更多关于 useEffect 的信息在这里What is the expected return of `useEffect` used for?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 2019-10-25
    • 2018-02-04
    • 2021-03-10
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2015-08-06
    相关资源
    最近更新 更多