如何在React Navigation中刷新

时间:2017-09-07 05:46:57

标签: reactjs react-native react-router react-navigation

删除用户令牌后,用户会重定向到“登录页面”。但是,如果我与其他用户登录,主页面仍会显示以前的用户信息。

这是因为我没有刷新主页面。如何在react-navigation中手动重新初始化(?)主页?

MainPage(Logged in as 'matt') -> Logout -> LoginPage 
-> (here I want to refresh MainPage so it can be loaded once new user login) 
-> MainPage(Should be logged in as other user 'kobe')

MainPage通过componentWillMount

接收用户JSON数据
  componentWillMount() {
    // retrieve user data 
    this.props.retrieveCurrentUser(this.props.token);
  }

万一你需要我的代码......

1)这是根导航

const RootTabNavigator = TabNavigator ({
    Auth: {
      screen: AuthStackNavigator,
    },
    Welcome: {
      screen: WelcomeScreen,
    },
    Main: {
      screen: MainTabNavigator,
    },
  }, {

2)这是Auth Stack Navigator(登录页面)

export default StackNavigator ({
  Autho: {
    screen: AuthScreen,
  },
  SignUp: {
    screen: SignUpScreen,
  },
  SignUpBio: {
    screen: SignUpUserBioScreen,
  },
  SignUpUsername: {
    screen: SignUpUsernameScreen,
  },
}, {
    header: null,
    headerMode: 'none',
    navigationOptions: {
      header: null
    },
    lazy: true
});

3)这是Main TabNavigator

export default TabNavigator(
  {
    Feed: {
      screen: FeedScreen,
    },
    Stylebook: {
      screen: StylebookScreen,
    },
    Wardrobe: {
      screen: WardrobeScreen,
    },
    Noti: {
      screen: NotificationScreen,
    },
    Menu: {
      screen: MenuScreen,
    },
  }, {
   ...
}

1 个答案:

答案 0 :(得分:12)

如果您使用flux或redux来管理您的状态,那么您将更新商店中的新状态(例如新用户名和其他任何数据更改),并且所有内容都会更新。

如果您不使用状态管理解决方案,那么您可以pass parameters in the navigate function。因此,当您在登录后导航到主页面时,传递一个标记或某些东西,让主页知道它需要更新。

这是链接文档中的示例:

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat', { user: 'Lucy' })}
          title="Chat with Lucy"
        />
      </View>
    );
  }
}

class ChatScreen extends React.Component {
  // Nav options can be defined as a function of the screen's props:
  static navigationOptions = ({ navigation }) => ({
    title: `Chat with ${navigation.state.params.user}`,
  });


  render() {
    // The screen's current route is passed in to `props.navigation.state`:
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text>Chat with {params.user}</Text>
      </View>
    );
  }
}

在您的情况下,当您导航到主页时:

navigate('MainPage', { token: '<new token>' })}

并在MainPage中:

componentWillReceiveProps(nextProps) {
  if (nextProps.navigation.state.params.token) {
    this.props.retrieveCurrentUser(this.props.token);
  }
}