从阵列变量React中获取JSON数据

时间:2018-01-29 11:19:33

标签: javascript arrays json reactjs fetch

我有一个代码为

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(数据[1]。名称);只返回:TypeError:data [1]未定义。

在我有json

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

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

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

4 个答案:

答案 0 :(得分:3)

.fetch()是异步的。此console.log(数据)在解析promise(data.push(result))

之前发生
fetch(url)
.then(response => response.json())
.then(result => data.push(result))
.then( () => console.log(data))

将记录数据。

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

答案 1 :(得分:0)

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

这意味着当console.logresponse尚未完成时,您的result会被触发。

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

答案 2 :(得分:0)

在你的提取中做这样的事情。

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可以更新。

答案 3 :(得分:-1)

    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);