我正在使用redux和react navigation来管理初始路由和屏幕。我的初始屏幕是飞溅之后,我重定向到主屏幕这里我从API获取数据,我想设置“登录用户名”,它在侧边栏中定义,侧边栏调用在DrawerNavigator中。
在主页上获取数据之后调用操作以更新redux中的数据,如下所示
Class Home extends Component{
comsponentDidMount(){
apiCall.then(response =>{
this.props.updateUser(response.user) //I am using api returning some user data as user
});
}
}
render(){
<SomeComponent/>
}
const mapStateToProps =(state)=>{
return state;
}
const mapDispatchToProps = (dispacth)=>{
return{
updateUser:(user)=>dispatch(()=>{type:"UPDATE_USER", user}) //your action creator may look like this
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home); //connect from react-redux
在侧边栏中获取用户使用redux
Class SideBar extends Component{
render(){
<View>
{this.props.user ? <UserComponent/>:<UnAuthenticatedUser/>}
</View>
}
}
const mapStateToProps =(state)=>{
return {
user:state.user //extract user from state
};
}
export default connect(mapStateToProps)(SideBar);
***根据您的Reducer和架构更改数据和功能
check redux doc了解更多