亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法調用 JSON 對象的第一個元素

無法調用 JSON 對象的第一個元素

慕斯709654 2021-12-12 15:24:45
我正在嘗試從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;
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

第一次嘗試訪問時data[0],它仍然是空的:


this.state = {

  post: [],

  isLoaded: false,

}

并且const data = this.state.post;意味著data[0]未定義。


只有在安裝了組件并且正確設置了data[0]定義的狀態(或不設置,取決于 API 返回的內容)之后。


查看完整回答
反對 回復 2021-12-12
?
www說

TA貢獻1775條經驗 獲得超8個贊

我找到了一種通過添加另一個“then”來使其工作的方法,因此它可以在設置“posts”狀態后立即設置“keys”狀態。但是我想知道是否有另一種方法可以使它更優雅。感謝您嘗試提供幫助。


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>

    )

  }


查看完整回答
反對 回復 2021-12-12
  • 2 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號