[英]React Native - Stack navigation when back handler is used
I have a simple app with a stack navigator.我有一个带有堆栈导航器的简单应用程序。 Which navigates like
哪个导航像
Screen A --> Screen B --> Screen C --> Screen D
I have added a back handler in Screen B like this我已经像这样在屏幕 B 中添加了一个后处理程序
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
It is working as expected on Screen B. When navigated to C or D, the hardware button won't cause navigation back to B or C respectively.它在屏幕 B 上按预期工作。当导航到 C 或 D 时,硬件按钮不会导致分别导航回 B 或 C。 Instead, it seems to fire the handleBackButtonClick in Screen B. How can I avoid this?
相反,它似乎触发了屏幕 B 中的 handleBackButtonClick。我怎样才能避免这种情况?
React Navigation keeps the previous screens rendered. React Navigation 保持之前的屏幕呈现。 So you need to make sure that the back handler is only enabled in the focused screen.
因此,您需要确保仅在焦点屏幕中启用后处理程序。
The official docs cover it.官方文档涵盖了它。
For v4: https://reactnavigation.org/docs/en/custom-android-back-button-handling.html对于 v4: https://reactnavigation.org/docs/en/custom-android-back-button-handling.html
For v5: https://reactnavigation.org/docs/en/next/custom-android-back-button-handling.html对于 v5: https://reactnavigation.org/docs/en/next/custom-android-back-button-handling.html
I think in your case the code could be simplified:我认为在您的情况下,代码可以简化:
handleBackButtonClick = () => {
// If this screen is not focused, don't do anything
if (!this.props.navigation.isFocused()) {
return false;
}
// Do what you're doing
}
``
I've faced the same issue,ie backhandler was trigeering the previous screens backhandler code.我遇到了同样的问题,即后处理程序正在触发以前的屏幕后处理程序代码。
SO what i did was checking for any existing backhandlers and then manually removing it in componentDidMount, rather than trusting the componentWillUnmount for that component..所以我所做的是检查任何现有的后处理程序,然后在 componentDidMount 中手动将其删除,而不是信任该组件的 componentWillUnmount..
componentDidMount(){
if (this.backHandler) // checking if backhnalder exists from previous screen
this.backHandler.remove();//removing it
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => { this.handleBackButton() });// adding the new backhandler
}
Hope this helps, otherwisae feel free to ask any doubts希望这会有所帮助,否则请随时提出任何疑问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.