【发布时间】:2019-06-06 13:25:00
【问题描述】:
现在我有以下内容:
componentWillUnmount() { console.log("Leaving"); this._isMounted = false; }
componentDidMount() { this._isMounted = true; }
我有这样的功能:
this.saveSomething(this.state.data).then((response) => {
if(response !== null) {
console.log(this._isMounted);
if(this._isMounted) {
Alert.alert(
'Success!', 'It was saved',
[
{text: 'Go Home', style: 'cancel', onPress: () => {
//navigate the app home
this.props.navigation.navigate('Home');
}},
{text: 'Stay Here'},
{text: 'Do something else', onPress: () => {
//stuff that they need to be on the page to do
}}
]
);
}
}
})
如果此功能运行并且我单击返回按钮并使用我的react-navigation、componentWillUnmount() 运行但一旦saveSomething 完成,如果我不在页面上,我的警报框仍然会弹出。
有人知道为什么会这样吗?
【问题讨论】:
-
你的渲染中是否调用了
saveSomething? -
@Treycos 通过触摸动作调用它
-
如果触摸动作完全正常,你的组件必须已经挂载
-
@Treycos 我不确定你想告诉我什么。如果我在 saveSomething 得到响应之前离开页面,我只需要找出一种方法,让 Success 警报不显示/在
isMountedif 语句之后执行任何操作。 -
您是否担心 react 生命周期功能不起作用?自己做
isMounted跟踪有点反模式。保存信息之类的反应约定是使用componentDidUnmount生命周期函数。