简体   繁体   English

无法调用 JSON object 的第一个元素

[英]Cannot call the first element of a JSON object

I'm trying to access the first object from data[] .我正在尝试从data[]访问第一个 object 。 Then, grab the keys using Object.keys() but it gives me this error:然后,使用Object.keys()获取密钥,但它给了我这个错误:

"TypeError: Cannot convert undefined or null to object". “TypeError:无法将未定义或 null 转换为对象”。

I need the output to be an array of the keys.我需要 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;

The first time you try to access data[0] , it's still empty:第一次尝试访问data[0]时,它仍然是空的:

this.state = {
  post: [],
  isLoaded: false,
}

and const data = this.state.post;const data = this.state.post; means that data[0] is undefined.表示data[0]未定义。

it's only after the component is mounted, and the state is set correctly that data[0] is defined (or not, depending on what the API returns).只有在安装组件之后,并且正确设置了 state 才能定义data[0] (或没有,取决于 API 返回的内容)。

The best approach to do this in React lifecycle is to place your code inside componentWillMount method instead of componentDidMount .在 React 生命周期中执行此操作的最佳方法是将代码放在componentWillMount方法而不是componentDidMount中。

componentDidMount() {
    const url = 'https://jsonplaceholder.typicode.com/users';
    fetch(url)
      .then(result => result.json())
      .then(post => {this.setState({ post: post })
    });
}

Remember the React lifecycle:记住 React 生命周期:

  • constructor
  • componentWillMount
  • render
  • componentDidMount

The difference is that componentDidMount executes after render .不同之处在于componentDidMountrender之后执行。 Where actually you are trying to render an empty variable.实际上,您正在尝试渲染一个空变量。

Most of the time, when you want to render information from a server, you must first obtain the data in componentWillMount and then you can render it.大多数时候,当你想从服务器渲染信息时,你必须先获取componentWillMount中的数据,然后才能render它。

Rendering arrays in React在 React 中渲染 arrays

You also have another mistake in your code, you are trying to render an Array, which actually React can't easily do.您的代码中还有另一个错误,您正在尝试渲染一个数组,这实际上 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: 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>
    );
}

I found a way for it to work by adding another "then" so it can set the "keys" state right after the "posts" state was set.我找到了一种通过添加另一个“then”来使其工作的方法,因此它可以在设置“posts”state 之后立即设置“keys”state。 But I wonder if there is another way to make it more elegant.但我想知道是否有另一种方法可以使它更优雅。 Thank you for trying to help.感谢您尝试提供帮助。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM