【问题标题】:Getting JSON data out of Array Variable React [duplicate]从数组变量 React 中获取 JSON 数据 [重复]
【发布时间】:2018-01-29 11:19:32
【问题描述】:

我有一个带有代码的jsx 文件

var React = require('react');
var CreateReactClass = require('create-react-class');


var url = "192.168.1.1:8081/json";
let data = [];

fetch(url)
.then(response => response.json())
.then(result => data.push(result));

console.log(data);
console.log(data[1].name);

console.log(数据); 返回数据,但我似乎无法从中获取任何特定属性。 console.log(data[1].name);只返回:TypeError: data[1] is undefined.

在我的网址上json

[
 {
  "id": "2",
  "name": "led",
  "color": "blue"
 },
 {
  "id": "3",
  "name": "le",
  "color": "red"
  }
]

由于某种原因,即使将 json 数据推入其中,我的数据数组的长度也是 0。

如何让控制台记录来自 "name":"le" 等数据变量的属性。

【问题讨论】:

  • 你的 React 组件的某些部分是否有这个 fetch 方法

标签: javascript arrays json reactjs fetch


【解决方案1】:

.fetch() 是异步的。这个console.log(data) 发生在promise 解决之前(data.push(result))

fetch(url)
.then(response => response.json())
.then(result => data.push(result))
.then( () => console.log(data))

将记录数据。

一种可能性是使用 ES7 的异步功能,如 here 所述。

【讨论】:

  • 我能够让整个 json 登录到控制台。但我无法从该 json 数据变量中获取特定属性。
  • 请阅读javascript中的异步。在承诺得到解决之前,您无法在 then 之外的其他工作中预测“数据”的值。当 fetch() 被触发时,then() 中的内容发生在 console.log 之后,类似于“另一个线程”。
【解决方案2】:

then 数据调用的结果是异步的。

这意味着您的console.logresponseresult 尚未完成时被触发。

fetch(url).then(json => {
    console.log(json);
});

【讨论】:

    【解决方案3】:

    在你的 fetch 中做这样的事情。

    fetch(url)
     .then(response => response.json())
     .then(result => {
        data = [ ...data, ...result ]; // spread the entire array;
        console.log('Result is=', data);
      });
    

    P.S:您的编码风格的整个方法不是很好。这不是您应该维护数据的方式,api 结果应该在某个state 变量中。因此,如果此数据发生任何更改,DOM 可以更新。

    【讨论】:

      【解决方案4】:
          var React = require('react');
          var CreateReactClass = require('create-react-class');
      
          var url = "192.168.1.1:8081/json";
          let data = [];
      
          fetch(url)
          .then(response => response.json())
          .then(result => data = result);
      
      console.log(data[1].name);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 1970-01-01
        • 2017-09-03
        • 2019-03-04
        • 1970-01-01
        • 2020-05-03
        相关资源
        最近更新 更多