在http成功响应之后,AsyncStorage不会将项目存储在react native中

时间:2017-06-27 06:10:54

标签: react-native

我刚刚尝试在成功后将项目存储在AsyncStorage中 我已经使用axios做了http请求。我有点困惑我已经尝试过如何使用AsyncStorage存储数据但是当我试图在http请求上存储一个项目onSucess()时不存储。请帮助我在哪里犯错误。

     axios.post(url, { email: this.state.email, password: this.state.password } , config)
    .then(function (response){
         // Alert.alert("success:",JSON.stringify(response.data.token));
     this.setState({ showProgress: false })
     this.setState({token:JSON.stringify(response.data.token)});
     var accesstoken=JSON.stringify(response.data.token);
     console.log(accesstoken);
     AsyncStorage.setItem("accesstoken",accesstoken);
     Alert.alert("success:", accesstoken);
  // Alert.alert("success:", JSON.stringify(accesstoken));
   }).catch(function (error) {
    Alert.alert("Error:",error);
   });

3 个答案:

答案 0 :(得分:0)

使用以下获取方法

fetch(url, {
    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((responseData) => {

    // Alert.alert("success:",JSON.stringify(response.data.token));
    this.setState({ showProgress: false })
    this.setState({token:JSON.stringify(response.data.token)});
    var accesstoken=this.state.token;
    console.log(accesstoken);
     AsyncStorage.setItem("accesstoken",accesstoken);
}).catch((error) => {
    Toast.show("There is a Problem on your network connection");
});

答案 1 :(得分:0)

以下是使用的示例:

`fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: <email> ,password: <password>})
}).then((response) => response.json())
  .then((responseData) => {
    if(responseData.STATUS == true){
        AsyncStorage.multiSet([
            ["state", JSON.stringify(responseData.DATA[0])],
            ["country", JSON.stringify(responseData.DATA[1])]
        ]);
    }
});`

答案 2 :(得分:0)

试试这个

   axios.post(url, { email: this.state.email, password: this.state.password } , config)
  .then(response => {
         // Alert.alert("success:",JSON.stringify(response.data.token));
     this.setState({ showProgress: false })
     this.setState({token:JSON.stringify(response.data.token)});
     var accesstoken=this.state.token;
     console.log(accesstoken);
  // Alert.alert("success:", JSON.stringify(accesstoken));
   }).catch(error => {
    Alert.alert("Error:",error);
   });