【问题标题】:How to get the value from previous value in json using fetch api?如何使用 fetch api 从 json 中的先前值中获取值?
【发布时间】:2018-11-18 19:42:46
【问题描述】:

在本机反应中,我从键中获取了值,但无法从先前的值中获取值。
例如我有以下 json

{
"username":"xyz",
"xyz":{"role":3,"role_name":"abcd"}
}

我需要获取用户名并使用用户名值需要访问角色。我试过跟随。

 constructor(){
    this.state={rol:'role',uname:'',xtext:'',}
}

  fetch('example.com/url')
  .then(response =>  response.json())
  .then(responseobj => {
    this.setState({
      uname: responseobj.username,
     xtest: responseobj[this.state.uname][this.state.rol],
   });

我得到了用户名,但没有得到角色。

【问题讨论】:

标签: javascript json react-native fetch-api


【解决方案1】:

setState 是异步的,所以 state 还没有准备好,你可以用这个:

  then(responseobj => {
    this.setState({
      uname: responseobj.username,
      xtest: responseobj[responseobj.username][this.state.rol],
   });

或者如果你真的想使用状态,你可以使用回调:

  then(responseobj => {
    this.setState({
      uname: responseobj.username,
   }, () => {
     this.setState({
       xtest: responseobj[this.state.uname][this.state.rol],
     })
   });

【讨论】:

    【解决方案2】:

    这不起作用,因为当您尝试在 setState 函数中使用 this.state.uname 时,它​​是一个空字符串。 setState 同时设置这两个值。试试这个:

        this.setState({
         uname: responseobj.username,
         xtest: responseobj[responseobj.username][this.state.rol],
       });
    

    【讨论】:

    • 没错,但在上面提供的示例中 this.state.uname === '' 所以它不会做 Shibin Raju Mathew 试图实现的目标
    • 恕我直言,请尝试在这里阅读我。我从来没有说过你不能从 setState 中获取现有状态。您所指的答案必须将 this 保存到一个变量中,因为他们在常规函数中使用 setState 而不是在我们的例子中是箭头函数(它自动将 this 绑定到类)。
    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2013-05-16
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    相关资源
    最近更新 更多