我需要从静态navigationOptions调用一个动作,但无法通过this.props访问我的动作。如何调用此动作?我收到错误"无法阅读财产'退出'未定义"在控制台中。
static navigationOptions = ({navigation}) =>( {
title: 'Home',
header: <Header headerTitle={navigation.state.routeName} logoutButtonPress={() => {
this.props.logout(); // this action is not working
NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: "Welcome" })]
})
navigation.navigate('Welcome');
}
}
/>,
});
&#13;
答案 0 :(得分:2)
在有navigationOptions的屏幕组件中
componentDidMount() {
this.props.navigation.setParams({
logOut: this.actionLogOut
});
}
actionLogOut = () => {
this.props.dispatch(logOut()); };
当componentDidMount然后
时,在导航参数中加载logout的函数动作static navigationOptions = ({ navigation }) => {
return {
headerTitle: (
<Text
style={{
left: Platform.OS == "android" ? 20 : 0
}}
>
Personal Data
</Text>
),
headerRight: (
<Aux>
<Icon
name="md-notifications"
size={27}
color="#9D9B9C"
style={{ paddingLeft: 15, marginRight: 15 }}
/>
<Icon
name="ios-log-out"
size={27}
color="red"
style={{ paddingLeft: 15, marginRight: 15 }}
onPress={() => {
console.log(navigation);
navigation.state.params.logOut();
navigation.dispatch(NavigationActions.back({ index: "Login" }));
navigation.popToTop();
}}
/>
</Aux>
)
};
};
在navigationOptions中使用navigation.state.params.logOut();
此组件必须使用“react-redux”中的import {connect}连接并使用组件
连接答案 1 :(得分:1)
您需要将logout
按钮设为component
并从props
模块react-redux
明确绑定mapDispatchToProps
例如
const LogoutButton = ({logout}) => {
return (
<TouchableOpacity style={{height: 50, width: 100}} onPress={() => logout()}>
<Text>Logout</Text>
</TouchableOpacity>
)
}
const mapDispatchToProps = dispatch => ({
logout: () => /*dispatch your logout action here*/
})
并在 static navigationOptions
中将其用作
static navigationOptions = ({navigation}) =>( {
title: 'Home',
header: <Header headerTitle={navigation.state.routeName}
/><Logout/>,
});
或修改您的组件以支持此组件。