簡體   English   中英

無法調用 JSON object 的第一個元素

[英]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

不同之處在於componentDidMountrender之后執行。 實際上,您正在嘗試渲染一個空變量。

大多數時候,當你想從服務器渲染信息時,你必須先獲取componentWillMount中的數據,然后才能render它。

在 React 中渲染 arrays

您的代碼中還有另一個錯誤,您正在嘗試渲染一個數組,這實際上 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM