异步设置ReactJS状态 [英] Set ReactJS state asynchronously
问题描述
如果您执行异步操作以更新 componentWillMount
中的状态(如文档所述),但是在该异步调用完成之前就已卸载了该组件(用户导航了),那么最终异步回调试图在现在已卸载的组件上设置状态,并使用
If you do an asynchronous action that updates the state in componentWillMount
(like the docs say), but the component is unmounted (the user navigates away) before that async call is complete, you end up with the async callback trying to set the state on a now unmounted component, and an
不变违规:replaceState(...):只能更新已安装的或安装组件."
"Invariant Violation: replaceState(...): Can only update a mounted or mounting component."
错误.
解决此问题的最佳方法是什么?
What's the best way around this?
谢谢.
推荐答案
更新2016
不要开始使用 isMounted
,因为它将从React中删除,
Don't start using isMounted
because it will be removed from React, see the docs.
对于 cmomponentWillMount
异步调用引起的问题,最好的解决方案是将内容移至 componentDidMount
.
Probably the best solution for problems arising from async call from cmomponentWillMount
is to move things to componentDidMount
.
有关如何正确解决此问题以及如何不需要在此处使用isMounted的更多信息:
More info about how to properly get around this problem and how not to need to use isMounted here: isMounted is an Antipattern
这篇关于异步设置ReactJS状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!