Promise.then无法正常工作

时间:2018-07-19 17:11:49

标签: reactjs react-native promise async-await es6-promise

我正在为我的react应用编写auth,获取令牌的功能可以在下面看到

axios.post("mywebsite.com/api/token-auth", {
        username: this.state.username,
        password: this.state.password
    })
    .then((fulfilled) => {

        userData = fulfilled.data;
        AsyncStorage.setItem("userData ", JSON.stringify(userData))
        .then(
            () => {
                this.scaleAnimationDialog.dismiss();
                // Set timeout is added to makesure the animation closes properly before navigating.
                setTimeout(
                    () => this.props.navigation.navigate("Home", userData), 500
                );
            }
        )
        .catch(
            () => {
                alert("Something went wrong, please try again");
                this.scaleAnimationDialog.dismiss();
            }
        )

    })
    .catch((error) => {
        this.scaleAnimationDialog.dismiss();
        alert("Authentication failed please try again");
    });

当我尝试使用有效的凭据登录时,它会按预期重定向到主屏幕,但是如果刷新应用程序,由于AsyncStorage没有密钥'userData',它将再次进入LoginScreen,

启动应用程序时,LoadingScreen是要加载的第一个组件,它决定要加载的屏幕。我根据react-navigation文档实现了此代码,其代码如下

_bootstrapAsync = async () => {
    const userDataString = await AsyncStorage.getItem('userData');
    const userDataObject = JSON.parse(userDataString);

    // This will switch to the App screen or Auth screen and this loading
    // screen will be unmounted and thrown away.
    this.props.navigation.navigate(userDataString ? "Home":"AuthNavigator", userDataObject);
  };

我在这里做错了什么。我是初次使用诺言,请保持答案更具描述性。

我还尝试了使用try / catch进行异步等待,但是在那种情况下,代码从未经过等待,并且加载弹出窗口也从未消失。请指出我的代码是否错误,并提出适当的解决方案。

谢谢!

2 个答案:

答案 0 :(得分:0)

您如何检查AsyncStorage中的密钥? 使用生命周期方法componentWillMount,在组件呈现之前进行操作。

类似这样的东西:

componentWillMount() {
    AsyncStorage.getItem('userData')
        .then(userData => {
            this.setState({ userData });
        })
        .catch((err) => {
            // Handle error here (maybe fetch user?)
        })
}

然后,在render方法内部相应地渲染this.state.userData。

希望这很有意义:)

答案 1 :(得分:0)

After some digging, I found out there is this issue with AsyncStorage for lot of other people, thanks to @Filipe for pointing to the right thread. After a lot of struggle I've decided to just use localstorage like sqlite or something and found this library https://github.com/sunnylqm/react-native-storage. It implements AsyncStorage internally and provides a wrapper to set and get data. Somehow this seems to work for me. If anyone is facing the same issue as me. Give that library a try.