[英]Cannot call the first element of a JSON object
我正在尝试从data[]
访问第一个 object 。 然后,使用Object.keys()
获取密钥,但它给了我这个错误:
“TypeError:无法将未定义或 null 转换为对象”。
我需要 output 作为键的数组。
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]
时,它仍然是空的:
this.state = {
post: [],
isLoaded: false,
}
和const data = this.state.post;
表示data[0]
未定义。
只有在安装组件之后,并且正确设置了 state 才能定义data[0]
(或没有,取决于 API 返回的内容)。
在 React 生命周期中执行此操作的最佳方法是将代码放在componentWillMount
方法而不是componentDidMount
中。
componentDidMount() {
const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then(result => result.json())
.then(post => {this.setState({ post: post })
});
}
记住 React 生命周期:
constructor
componentWillMount
render
componentDidMount
不同之处在于componentDidMount
在render
之后执行。 实际上,您正在尝试渲染一个空变量。
大多数时候,当你想从服务器渲染信息时,你必须先获取componentWillMount
中的数据,然后才能render
它。
您的代码中还有另一个错误,您正在尝试渲染一个数组,这实际上 React 不容易做到。
Object.keys()
returns an array of the object keys, so if you want to render all of them, you should use map
function for arrays:
render() {
const data = this.state.post;
var keys = Object.keys(data[0]);
return (
<div>
{keys.map(e => (<h5>{e}</h5>) )}
</div>
);
}
我找到了一种通过添加另一个“then”来使其工作的方法,因此它可以在设置“posts”state 之后立即设置“keys”state。 但我想知道是否有另一种方法可以使它更优雅。 感谢您尝试提供帮助。
constructor(props) {
super(props);
this.state = {
posts: [],
isLoaded: false,
keys: []
}
}
componentDidMount() {
const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then(result => result.json())
.then(posts => {
this.setState({ posts: posts })
})
.then(_ => { this.setState({ keys: Object.keys(this.state.posts[0]) }) })
}
render() {
const keys = this.state.keys;
return (
<div>
<h5>{keys}</h5>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.