React Spring“无法在已卸载的组件上执行React状态更新”

时间:2020-05-19 02:21:33

标签: reactjs state use-effect react-spring react-component-unmount

快速点击时,我一直在使用React Spring:

警告:无法在已卸载的组件上执行React状态更新。 这是空操作,但它表明应用程序中发生内存泄漏。 要修复,请取消useEffect中的所有订阅和异步任务 清理功能。

这是我发现的具有相同问题的示例沙箱。如果您快速单击“单击此处”,您将看到我面临的相同问题。

https://codesandbox.io/s/greeting-card-with-react-spring-f2vr0?from-embed

沙箱来自此博客:

https://blog.logrocket.com/animations-with-react-spring/

假设我很想念这很愚蠢,但是想知道这是否是react-spring的问题,因为它与useEffect有关。

1 个答案:

答案 0 :(得分:1)

您使用的是三元组,因此该组件已卸载。

如果greetingStatus为true,则不渲染任何内容。还要始终渲染动画div(因为您要用1或0切换不透明度)

Working copy of your code is here in sandbox

代码段

import React from "react";
import ReactDOM from "react-dom";
import { useSpring, animated as a } from "react-spring";

import "./styles.css";

const App = () => {
  const [greetingStatus, displayGreeting] = React.useState(false);
  const contentProps = useSpring({
    opacity: greetingStatus ? 1 : 0,
    marginTop: greetingStatus ? 0 : -500,
    position: "absolute"
  });
  return (
    <div className="container">
      <div className="button-container">
        <button onClick={() => displayGreeting(a => !a)} className="button">
          Click Here
        </button>
      </div>
      {!greetingStatus ? <div className="Intro">Click button below</div> : null}
      <a.div className="box" style={contentProps}>
        <h1>Hey there ! React Spring is awesome.</h1>
      </a.div>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);