我有一个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]未定义。
在我的URL地址上json
[
{
"id": "2",
"name": "led",
"color": "blue"
},
{
"id": "3",
"name": "le",
"color": "red"
}
]
由于某种原因,即使将 json 数据插入其中,我的数据数组的长度仍为 0。
如何让控制台记录数据变量中的属性,如 "name":"le"
.
最佳答案
.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 .
关于javascript - 从 Array Variable React 中获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48500043/