在组件中反应本机设置状态

问题描述 投票:-1回答:1

我正在使用redux和react navigation来管理初始路由和屏幕。我的初始屏幕是飞溅之后,我重定向到主屏幕这里我从API获取数据,我想设置“登录用户名”,它在侧边栏中定义,侧边栏调用在DrawerNavigator中。

react-native redux react-navigation
1个回答
0
投票

在主页上获取数据之后调用操作以更新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了解更多

© www.soinside.com 2019 - 2024. All rights reserved.