现在我有以下内容:
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
完成,如果我不在页面上,我的警报框仍然会弹出。
有谁知道为什么会发生这种情况吗?
最佳答案
堆栈中更靠下的组件可以接收对 componentWillReceiveProps 等方法的调用,并在未显示时进行渲染。
我认为最好的方法是在 componentDidMount
中处理 isMounted 并添加一个导航监听器,例如 didBlur,它在屏幕未聚焦时触发:
const didBlurSubscription = this.props.navigation.addListener(
'didBlur',
payload => {
this._isMounted = false;
}
);
并确保您删除了 componentWillUnmount 内的监听器。
在此处阅读有关导航生命周期的更多信息:https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle
关于javascript - 离开页面时 React Native 不运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54149626/