开发者问题收集

React Native-刷新屏幕

2016-07-25
6831

我有以下应用程序:

主页 -> 登录 -> 收藏夹

在主屏幕上,您可以单击“收藏夹”按钮,该按钮:

1) 如果您已登录,它将显示您的收藏夹

2) 如果您尚未登录,它将显示登录屏幕

假设某人未登录,他们登录到应用程序,这将设置来自 API 的密钥并返回一条警报,提示“您现在已登录...”。

登录后返回主屏幕时,如果他们单击“收藏夹”,它仍会向他们显示登录屏幕。他们必须关闭应用程序并重新启动应用程序才能使登录生效。

确保他们不必继续登录的最佳方法是什么?

这是主文件:

  renderView() {


    if(this.state.token != null)
    {
        var data = this.getData();
    }else{
        console.log("token " + this.state.token);
        this.refs.nav.navigator.push({
          title: "Login",
          component: Login,
          rightButtonTitle: 'Cancel',
          passProps: {nav: navigator},
          onRightButtonPress: () => { this.refs.nav.navigator.pop(); }
        });
    }

  }


render() {
    return (

      <NavigatorIOS
          ref="nav"
          style={styles.container}
          initialRoute={{
              title: 'Home',
              component: Main,
              rightButtonTitle: this.renderIcon(),
              onRightButtonPress: () => {
                  this.renderView();
              }

          }} />

    );

  }

getData() {

  var query = urlForQueryAndPage('token', this.state.token, 1);

  fetch(query)
    .then(response => response.json())
    .then(json => this._handleResponse(json.response))
    .catch(error =>
      this.setState({
        isLoading: false,
        message: 'Something bad happened ' + error
    }));
}

这是主文件,检查是否存在令牌,它将导航到收藏夹,否则它将导航到登录。

我在 Login.js 中的 Handle 登录:

    handleLogin(reply) {

      if(reply.body.response == 'true')
      {
          this.setServerKey(reply.body.key);
          AlertIOS.alert(
              "Login",
              "You are now signed in. Please go back to access your favourites!"
          );
      }else{

        AlertIOS.alert(
            "Login",
            "Wrong username/password. Please try again!"
        );

      }

  }

如您所见,登录只会弹出一个窗口。但我需要以某种方式刷新主屏幕,以确保收藏夹显示出来,而无需用户再次登录。

1个回答

登录后避免重新登录

let token;

constructor(props) {
  super(props);
  this.checkToken();
}

async checkToken() {
  try {
    const value = await AsyncStorage.getItem('@MySuperStore:token');
    if (value !== null){
      token = value;
    } 
  } catch (error) {
    // Error getItem from AsyncStorage
  }
}

renderView() {
  if(token != null) {
    var data = this.getData();
  } else {
    //re-check because constructor only run once
    this.checkToken();
    if (token) {
      We have data!! therefore we getData() and redirect to favourites page
    } else {
      this.refs.nav.navigator.push({
        title: "Login",
        component: Login,
        rightButtonTitle: 'Cancel',
        passProps: {nav: navigator},
        onRightButtonPress: () => { this.refs.nav.navigator.pop(); }
      });
    }
  }
}

如果您可以以持久方式而不是易失性状态保存令牌,那么您可以在第一次获取令牌后检索该值并检查它。

在我看来,我有两种方法可以以持久方式保存令牌。

  1. AsyncStorage

First, check if your token exists in AsyncStorage

try {
  const value = await AsyncStorage.getItem('@MySuperStore:token');
  if (value !== null){
    // We have data!! therefore we redirect to favourites page
  } else {
    // call getData() and handleLogin()
    // remember setItem token to AsyncStorage
    await AsyncStorage.setItem('@MySuperStore:key', token);
  }
} catch (error) {
  // Error retrieving data or setItem to AsyncStorage
}
  1. Redux redux-persist

you can retrieve token from the redux store that is persisted by redux-persist, but this might be time-consuming if you want to understand and implement the redux but it's worth it.

V-SHY
2016-07-25