javascript - 异步设置 ReactJS 状态

标签 javascript asynchronous reactjs setstate

如果您执行更新 componentWillMount 中的状态的异步操作(如文档所述),但在异步调用完成之前组件已卸载(用户导航离开),您最终会异步回调试图在一个现在未安装的组件上设置状态,一个

"Invariant Violation: replaceState(...): Can only update a mounted or mounting component."

错误。

解决这个问题的最佳方法是什么?

谢谢。

最佳答案

您可以使用 component.isMounted 方法在替换组件状态之前检查组件是否实际附加到 DOM。 Docs .

isMounted() returns true if the component is rendered into the DOM, false otherwise. You can use this method to guard asynchronous calls to setState() or forceUpdate().

UPD:在你投反对票之前。这个答案是 2 年前给出的。这就是当时做事的方式。如果您刚刚开始使用 React,请不要遵循此答案。使用 componentDidMount 或您需要的任何其他生命周期 Hook 。

关于javascript - 异步设置 ReactJS 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25067364/

相关文章:

JavaScript 算法 : print out the path from directed graph with minimal costs

javascript - 如何创建在您向下滚动页面时更改的标题?

reactjs - 从 redux 状态更改后如何以及何时调用 React 组件方法

javascript - 加载数组数据 init immutable.js

javascript - 替换 "with\"

javascript - 将 XML 字符串转换为 JSON 的工具 (javascript)

python - Quamash 和 PyQt5 - 进程结束时出现额外窗口

asynchronous - Future.delayed() 在 dart 中的行为

c# - 用于实时应用程序的异步与同步套接字服务器

javascript - 无法在模型中提交表单 react