React:卸载组件时状态不是最新的

React: State is not up-to-date when I unmount component

在我的工作中,当有人离开页面时,我必须发出一个 http 请求。我的想法是在该页面的组件卸载时执行此请求。

如果我理解正确的话,这可以通过将逻辑放在 useEffect 的 return 函数中来完成。当我这样做时,它会在正确的时间触发,但我想使用的状态值不是最新的。有没有办法获取最新值?

      useEffect(() => {
    
        return () => {
    
          //this runs on unmount
         // but the state changes that happened are not registered it seems
        }
      }, [])

我在 codesandbox 中创建了一个简单的示例:当您将状态从 4 更改为 8 然后隐藏组件时。卸载中的 NUM 值仍然是 4(检查控制台日志)。卸载组件时如何获取当前状态值?

https://codesandbox.io/live/b6e65d13114

https://codesandbox.io/s/loving-galois-okb0b(不确定哪个 link 最好分享)

每次显示NumCheck组件,num都会重新赋值为4。

我认为您可以通过将 num 状态作为 prop 发送到 NumCheck 组件来解决您的问题。这样,无论 NumCheck 组件是否再次重新呈现,num 的状态都分配给父组件(在您的情况下它将保持 8)。

Numcheck 组件:

    import "./styles.css";
    import { useEffect, useState } from "react";
    
    export const NumCheck = ({ num, setNum }) => {
      useEffect(() => {
        return () => {
          console.log("NUM CHECK", num);
        };
      }, []);
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>click the button to change number</h2>
          <button onClick={() => setNum(8)}>click me</button>
    
          <br />
          <br />
          <h5>{num}</h5>
        </div>
      );
    };

应用组件

export default function App() {
  const [show, setShow] = useState(true);
  const [num, setNum] = useState(4);
  return (
    <>
      {show ? (
        <div>
          <NumCheck num={num} setNum={setNum}  />
          <button onClick={() => setShow(!show)}>hide the component!</button>
        </div>
      ) : (
        <div>
          <h5>hidden</h5>
          <button onClick={() => setShow(!show)}>show the component!</button>
        </div>
      )}
    </>
  );
}

您可以使用 React ref 来缓存状态的副本以在清理函数中访问。

import { useEffect, useRef, useState } from "react";

export const NumCheck = () => {
  const [num, setNum] = useState(4);
  const stateRef = useRef(); // <-- ref to cache state value

  useEffect(() => {
    stateRef.current = num; // <-- cache state value on change
  }, [num]);

  useEffect(() => {
    return () => {
      console.log("NUM CHECK", stateRef.current); // <-- access cached state value
    };
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>click the button to change number</h2>
      <button onClick={() => setNum(8)}>click me</button>

      <br />
      <br />
      <h5>{num}</h5>
    </div>
  );
};