javascript - 将 JSON 响应中的值存储到 AsyncStorage React Native

标签 javascript reactjs react-native asynchronous

我正在尝试在 AsyncStorage 中存储用户 ID(类型为数字),但这会引发以下错误:

异常'-[_NSCFNumber length]:在目标上调用多重集时抛出发送到实例 0xb0000000000000023 的无法识别的选择器

带参数的 AsyncLocalStorage (((userid, 2))

请帮我解决这个问题。

class SignIn extends Component {

  loginHandler = async () => {
    this.setState({ loading: true });
    try {
      let { data } = await axios
        .post("http://offer.kdamjibhai.com/api/login", {
          username: this.state.username,
          password: this.state.password
        })
        .then(response => {
          if (response.data.status_code === 200) {
            if (response.data.data.status === "success") {
              //alert('came here ')
              AsyncStorage.setItem("loggedIn", "true");
              AsyncStorage.setItem('userid', response.data.data.user_info.user_id);
              
              this.setState({ loading: false });
              this.props.navigation.navigate("SignedIn");
            } 
          } else {
            alert(response.data.data.message);
            this.setState({ loading: false });
          }
        });
    } catch (err) {
      console.log(err);
    }
    
  };

  render() {}

}

export default SignIn;

最佳答案

我试过你的代码,返回的useid是Number,AsyncStorage只能存储字符串。所以需要先将userid转成string,然后才能保存。您应该使用 .then().catch() 来处理错误而不是 try{} catch{} 并删除 async, await 关键字,因为你正在使用 .then().catch() 语法。

loginHandler = () => {
  this.setState({ loading: true });
  axios
  .post("http://offer.kdamjibhai.com/api/login", {
    username: this.state.username,
    password: this.state.password
  })
  .then(response => {
    if (response.data.status_code === 200) {
      if (response.data.data.status === "success") {
        //alert('came here ')
        AsyncStorage.setItem("loggedIn", "true");
        AsyncStorage.setItem('userid', response.data.data.user_info.user_id.toString());
        this.setState({ loading: false });
        this.props.navigation.navigate("SignedIn");
      }
    } else {
      alert(response.data.data.message);
      this.setState({ loading: false });
    }
  })
  .catch((error) => {
    console.log(error);
  })
};

关于javascript - 将 JSON 响应中的值存储到 AsyncStorage React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808613/

相关文章:

Javascript 函数调用需要唯一的名称

c# - 是否可以重新加载服务器端 jquery 数据表?

javascript - jointjs:svg 文本在落到纸上时被空白替换

javascript - React-native 不应该只渲染与 React 工作方式类似的更改组件吗?

javascript - 访问 DOM 节点的引用时,React Refs 返回 null 或未定义

c# - 以特定格式从剑道日历获取日期时间

javascript - 如何检查组件 react 中浪费的渲染

ios - 如何更新应用商店中已有应用的截图?

ios - React Native - 预期参数类型“RCTViewManagerUIBlock”

ios - 如何在 React Native 项目中重新生成 ios 文件夹?