Class 组件中的 React Navigation (5+) navigation.addListener()
React Navigation (5+) navigation.addListener() in Class Components
我想在导航中添加一个监听器 beforeRemove
以防止用户返回。
然后他们得到一个 alert
继续或丢弃。
我遵循了 tutorial from reactnaviagtion.org 但这是在 功能组件 .
中
在我的案例中,它是一个反应本机 Class-Component.
我可以通过道具轻松调用函数:
componentDidMount(){
this.props.navigation.addListener("beforeRemove", (e) =>{
console.log("beforeRemoveTriggered");
this.state.SomeVariablesToCheckIfGameStarted
Alert.alert(..., onPress: ()=> this.props.navigation.dispatch(e.data.action));
}
}
console.log
没有问题,但我无法在回调中调用状态。
beforeRemoveTriggered
但之后我得到以下错误:
TypeError: undefined is not an object (evaluating '_this2.props.someVariablesToCheckIfGameStarted`)
- node_modules\...
我的猜测是你不能在监听器回调中调用状态。
但这是应用程序功能所必需的,所以我不能“只是不使用状态”。
顺便说一句,使用 useEffect
的解决方法是可以接受的,但不是首选。
这可能有一个简单的解决方案,它不是特定于 react-navigation 或 react-native 但 javascript.
任何提示都会有所帮助,提前致谢!!!
我知道我的答案...
也许但也许我叫 this.props
而不是 this.state
也许在这个发现之后一切正常......
很抱歉让我费心弄清楚解决方案是什么!
我想在导航中添加一个监听器 beforeRemove
以防止用户返回。
然后他们得到一个 alert
继续或丢弃。
我遵循了 tutorial from reactnaviagtion.org 但这是在 功能组件 .
中
在我的案例中,它是一个反应本机 Class-Component.
我可以通过道具轻松调用函数:
componentDidMount(){
this.props.navigation.addListener("beforeRemove", (e) =>{
console.log("beforeRemoveTriggered");
this.state.SomeVariablesToCheckIfGameStarted
Alert.alert(..., onPress: ()=> this.props.navigation.dispatch(e.data.action));
}
}
console.log
没有问题,但我无法在回调中调用状态。
beforeRemoveTriggered
但之后我得到以下错误:
TypeError: undefined is not an object (evaluating '_this2.props.someVariablesToCheckIfGameStarted`)
- node_modules\...
我的猜测是你不能在监听器回调中调用状态。
但这是应用程序功能所必需的,所以我不能“只是不使用状态”。
顺便说一句,使用 useEffect
的解决方法是可以接受的,但不是首选。
这可能有一个简单的解决方案,它不是特定于 react-navigation 或 react-native 但 javascript.
任何提示都会有所帮助,提前致谢!!!
我知道我的答案...
也许但也许我叫 this.props
而不是 this.state
也许在这个发现之后一切正常......
很抱歉让我费心弄清楚解决方案是什么!