将应用程序转换为 redux 后,我的 react-navigation
出现了一些问题。以前,在与 redux 集成之前,当我按下后退按钮(物理按钮)时, react 导航回到上一个屏幕。与 redux 集成后,返回按钮将关闭应用程序。但是,它仍在使用 goBack()
函数。
- 我正在遵循指南:https://reactnavigation.org/docs/guides/redux
- 并从这里阅读一些代码:https://github.com/react-community/react-navigation/tree/master/examples/ReduxExample
这是我的导航器配置
export const AppNavigator = StackNavigator(
{
Home: { screen: HomeScreen },
ChatDetail: { screen: ChatDetail },
PulsaDetail: { screen: PulsaDetailScreen },
Pulsa: { screen: Pulsa }
},
{
headerMode: 'none',
}
)
class AppWithNavigation extends Component {
render(){
return(
<AppNavigator navigation={ addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.nav,
})} />
)
}
}
const mapStateToProps = (state) => ({
nav: state.nav
})
export default connect(mapStateToProps)(AppWithNavigation)
编辑:可以通过手动处理和发送回操作来完成,但不能自动完成吗?就像之前使用 redux 一样?
BackHandler.addEventListener('hardwareBackPress',() => {
this.props.goBack()
return true
})
最佳答案
在 react-navigation 存储库中发布 Github 问题后,我得到了答案。
应该在屏幕/组件顶部手动添加后台监听器
// App.js
import { BackAndroid } from 'react-native'
// [...]
componentDidMount() {
BackAndroid.addEventListener('backPress', () => {
const { dispatch, nav } = this.props
if (shouldCloseApp(nav)) return false
dispatch({ type: 'Back' })
return true
})
}
componentWillUnmount() {
BackAndroid.removeEventListener('backPress')
}
// [...]
- https://github.com/react-community/react-navigation/issues/2117
- https://github.com/react-community/react-navigation/issues/117
更新:
关于android - React Navigation + Redux 在按下返回时关闭应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45018792/