【发布时间】:2019-10-31 23:24:30
【问题描述】:
我正在尝试从data[] 访问第一个对象。然后,使用Object.keys() 获取密钥,但它给了我这个错误:
“类型错误:无法将未定义或空值转换为对象”。
我需要输出是键的数组。
import React, { Component } from 'react';
class CodecChart extends Component {
constructor(props) {
super(props);
this.state = {
post: [],
isLoaded: false,
}
}
componentDidMount() {
const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then(result => result.json())
.then(post => {this.setState({ post: post })
})
}
render() {
const data = this.state.post;
// cannot reach the first object of data[]
var keys = Object.keys(data[0]);
return (
<div>
//output should be an array of the keys
<h5>{keys}</h5>
</div>
)
}
}
export default CodecChart;
【问题讨论】:
-
这意味着
data[0]未定义 - 没有 JSON 对象之类的东西
标签: javascript json reactjs api