Reactjs 如何避免异步操作在未安装的组件上设置状态?
让我们设想一个组件使用fetch从服务器加载数据 但有可能在卸载组件后加载数据,这将导致尝试在卸载的组件上设置状态Reactjs 如何避免异步操作在未安装的组件上设置状态?,reactjs,react-native,asynchronous,synchronization,Reactjs,React Native,Asynchronous,Synchronization,让我们设想一个组件使用fetch从服务器加载数据 但有可能在卸载组件后加载数据,这将导致尝试在卸载的组件上设置状态 这种问题有多严重以及如何避免它发生?这是不可行的,因为它什么也不做,但是如果状态有点“大”或资源重,那么它可能会导致很少的内存泄漏 我在使用react navigation v2模块的DroperNavigator时遇到过这种情况,我通过使用一个变量来告诉我组件是已安装还是已卸下,从而进行了一次肮脏的变通 class Modal extends React.PureComponen
这种问题有多严重以及如何避免它发生?这是不可行的,因为它什么也不做,但是如果状态有点“大”或资源重,那么它可能会导致很少的内存泄漏 我在使用react navigation v2模块的DroperNavigator时遇到过这种情况,我通过使用一个变量来告诉我组件是已安装还是已卸下,从而进行了一次肮脏的变通
class Modal extends React.PureComponent {
....
_mounted=false;
componentDidMount(){this._mounted = true}
componentWillUnmount(){this._mounted = false}
....
然后每次我调用setstate时,我都会在执行之前检查这是否为真
现在,在react navigation v3中,抽屉没有卸载屏幕,因此我很高兴不用它您会想看看屏幕。使用反模式时:
class Test extends React.ComponentComponent {
componentDidMount() {
this.controller = new AbortController();
fetch(`${url}`, { signal: controller.signal }).then(response => {
this.setState({ })
})
}
componentWillUnmount() {
this.controller.abort()
}
}
调用控制器的中止
功能将取消提取
。我建议在组件willunmount
生命周期函数中调用它
浏览器兼容性:正如您在评论中提到的,我看到了同一篇博文,这篇博文给了我不使用ismounted()的相同想法
对于任何升级代码以避免ismounted()的人来说,一个简单的迁移策略就是自己跟踪装载状态。只需在componentDidMount中将_isMounted属性设置为true,并在componentWillUnmount中将其设置为false,然后使用此变量检查组件的状态。
,本文旨在避免isMounted()。不是这个-
class Test extends React.ComponentComponent {
componentDidMount() {
this.controller = new AbortController();
fetch(`${url}`, { signal: controller.signal }).then(response => {
this.setState({ })
})
}
componentWillUnmount() {
this.controller.abort()
}
}