无法调用 JSON 对象的第一个元素

我正在尝试从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;


慕斯709654
浏览 183回答 2
2回答

幕布斯6054654

第一次尝试访问时data[0],它仍然是空的:this.state = {&nbsp; post: [],&nbsp; isLoaded: false,}并且const data = this.state.post;意味着data[0]未定义。只有在安装了组件并且正确设置了data[0]定义的状态(或不设置,取决于 API 返回的内容)之后。

www说

我找到了一种通过添加另一个“then”来使其工作的方法,因此它可以在设置“posts”状态后立即设置“keys”状态。但是我想知道是否有另一种方法可以使它更优雅。感谢您尝试提供帮助。constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; posts: [],&nbsp; &nbsp; &nbsp; isLoaded: false,&nbsp; &nbsp; &nbsp; keys: []&nbsp; &nbsp; }&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; const url = 'https://jsonplaceholder.typicode.com/users';&nbsp; &nbsp; fetch(url)&nbsp; &nbsp; &nbsp; .then(result => result.json())&nbsp; &nbsp; &nbsp; .then(posts => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ posts: posts })&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .then(_ => { this.setState({ keys: Object.keys(this.state.posts[0]) }) })&nbsp; }&nbsp; render() {&nbsp; &nbsp; const keys = this.state.keys;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <h5>{keys}</h5>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript