反应弹簧"Can't perform a React state update on an unmounted component"



我在快速点击时遇到了使用 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 有关。

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

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

您的代码的工作副本在沙盒中

代码片段

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

最新更新