【问题标题】:React Spring "Can't perform a React state update on an unmounted component"React Spring“无法在未安装的组件上执行 React 状态更新”
【发布时间】:2020-09-04 23:52:16
【问题描述】:

快速点击时我一直在使用反应弹簧:

警告:无法对未安装的组件执行 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 有关。

【问题讨论】:

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


    【解决方案1】:

    您正在使用三元,因此该组件已卸载。

    如果greetingStatus 为真,则不渲染。也总是渲染你的动画 div(因为你用 1 或 0 切换不透明度)

    Working copy of your code is here in sandbox

    代码 sn-p

    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);
    
    

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2021-07-01
      • 2020-11-21
      • 2021-11-30
      • 2020-09-03
      • 2019-11-09
      • 2019-05-30
      • 2021-05-30
      相关资源
      最近更新 更多