首页 > 解决方案 > How to handle props navigation inside of if condition using React Native

问题描述

I have question regarding on props navigation, I was wondering how can i navigate other screen if condition is true? I have module where the user need to login, I am using ReactJS api. Moving forward, I can get the right response in the api, however there is problem on my if statement that my props is undefined is not an object.

I have here my codes that I made,

    AsyncStorage.getItem('authorization_code', (err, result) => {
      let token = result;
      axios({
          method: 'post',
          url: 'http://1xx.xx.x.xx:8002/api/auth/me?token=',
          headers: {"Authorization" : `Bearer ${token}`}
      }).then(response => {
          const email = response.data.email;
          const user_type = response.data.user_type;

          AsyncStorage.setItem('USERMAIL',email.toString());
          AsyncStorage.setItem('USERTYPE',user_type.toString());

          if(user_type == 1) {
            this.props.navigation.push('Dashboard');
          }
          else if(user_type == 3) {
            this.props.navigation.push('Dashboard');
          }

      })
});

Thanks.

标签: javascriptreactjsreact-native

解决方案


这是因为您正在this另一个闭包中访问。要解决此问题,您可以存储一个局部变量并从传递给的函数中访问它then。一个常见的约定是创建一个名为的新变量thatthis您希望将其持续到闭包。

getItemFromStorage() {

  // this line is the key
  const that = this;

  AsyncStorage.getItem('authorization_code', (err, result) => {
    let token = result;
    axios({
        method: 'post',
        url: 'http://1xx.xx.x.xx:8002/api/auth/me?token=',
        headers: {"Authorization" : `Bearer ${token}`}
    }).then(response => {
        const email = response.data.email;
        const user_type = response.data.user_type;

        AsyncStorage.setItem('USERMAIL',email.toString());
        AsyncStorage.setItem('USERTYPE',user_type.toString());

        // now you can access that to obtain the props
        if(user_type == 1) {
          that.props.navigation.push('Dashboard');
        }
        else if(user_type == 3) {
          that.props.navigation.push('Dashboard');
        }
    })
  });
}

更多关于这里


推荐阅读