React Navigation头部右侧Logout按钮点击无响应问题求助
咱们一步一步来排查你遇到的问题,核心问题其实很明显,先帮你搞定最关键的部分:
1. 致命错误:Redux映射的方法名大小写不匹配
你在mapDispatchToProps里定义的方法键是Signout(首字母大写):
const mapDispatchToProps = (dispatch) => { return { Signout : ()=> dispatch(Signout()) } }
但在组件的_Logout方法里调用的却是this.props.signOut(首字母小写):
_Logout() { this.props.signOut(); }
这两个名称必须完全一致,把它们统一成相同的大小写就能解决最根本的调用问题,比如都改成小写:
const mapDispatchToProps = (dispatch) => { return { signOut : ()=> dispatch(Signout()) } }
2. 优化方法绑定,避免上下文丢失
你用bind(this)的方式绑定_Logout,其实可以直接用箭头函数定义方法,这样就不用手动绑定上下文了,更简洁可靠:
_Logout = () => { this.props.signOut(); }
对应的componentDidMount也能简化:
componentDidMount(){ this.props.navigation.setParams({ logout : this._Logout }) }
3. 可选优化:直接在组件内定义导航选项
如果你的屏幕组件已经连接了Redux,还可以把headerRight的定义移到组件内部的静态navigationOptions里,逻辑会更清晰:
class WelcomeScreen extends Component { static navigationOptions = ({ navigation }) => { return { title : 'Welcome', headerStyle: { backgroundColor: '#29434e', shadowColor: 'transparent', elevation: 0 }, headerRight: ( <TouchableOpacity style={{ backgroundColor: '#DDDDDD', padding: 5 }} onPress={() => navigation.getParam('logout')} > <Text style={{ fontSize: 10 }}> Logout </Text> </TouchableOpacity> ), } } componentDidMount(){ this.props.navigation.setParams({ logout : this._Logout }) } _Logout = () => { this.props.signOut(); } // ...其他组件代码 }
先修复第一个大小写匹配的问题,点击Logout按钮应该就能正常触发方法了,后面的优化可以根据你的需求选择调整。
内容的提问来源于stack exchange,提问作者Ali Yar Khan
相关产品推荐
相关产品推荐

