首页 > 解决方案 > 重定向到另一个页面之前的异步存储

问题描述

我正在尝试创建一个登录页面,其中 userId 将通过 asyncstorage 存储,并将在重定向页面上获取该值并将其放置在隐藏的属性中,以便在另一个按钮单击时使用。

这是我在登录页面中的 TouchableOpacity,它有一个 onPress 功能

<TouchableOpacity 
    style={styles.userBtn}
    onPress={this._login}
 ><Text style={styles.btnText}>Log In</Text>
 </TouchableOpacity>

点击/按下这里的功能

_login = async () => {
  await AsyncStorage.setItem('isLoggedIn', '1');
  fetch('http://XXX.XXX.XXX.X:XX/api/public/signin', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: this.state.email,
        password: this.state.password,
      })
})
  .then((response) => response.json())
    .then((responseJson) => {
        if (responseJson['success'] == true) {


            AsyncStorage.setItem('authId', responseJson['authId'])

            this.props.navigation.navigate('Details')
        }else{
            AsyncStorage.clear();
            alert('Username or Password is incorrect');
        }
    })
    .catch((error) => {
        console.error(error);
    });
}

这是我获取 authID 的详细信息页面功能

这是在 render() 之前

constructor(props){
super(props);
this.state={currentTime: null, currentDay: null, longitude: 0, latitude: 0, error: null }
this.daysArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
this._getUserId();
}

这是在 render() 之后

_getUserId = async() => {
  const userId = await AsyncStorage.getItem('authId');
  alert(userId);
}

所以基本上在 render() 部分之前,在构造函数中,我调用了 render() 部分之后的函数。但它总是对我返回一个空警报。

抱歉,我开始学习 React Native 才一周。我正在练习我的技能,所以如果我解释它的方式有问题,如果我问这个问题,我很抱歉。

标签: react-nativeasync-await

解决方案


您是否尝试将 _getUserId 放入 componentDidMount 方法中?有时最好调用 componentDidMount 中的所有函数,该函数需要在组件渲染后执行。并且还尝试 isLogged 首先检查您的身份验证 ID 是否存在问题,因为它可能为空。如果 isLoggedIn 为 1,那么有一个带有您的身份验证 ID 的问题,

例如。

class ABC extends Component {
constructor(props){
super(props);
this.state={currentTime: null, currentDay: null, longitude: 0, latitude: 0, error: null }
this.daysArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

}

async componentDidMount(){
let result = await this._getUserId();
}


_getUserId = async() => {
  const userId = await AsyncStorage.getItem('authId');
  const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
  alert(userId,isLoggedIn);
}


render(){
}
}

推荐阅读