第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

訪問 JavaScript 數(shù)組返回“未定義”

訪問 JavaScript 數(shù)組返回“未定義”

白衣非少年 2021-05-31 18:04:05
我正在用純 Reactjs 構(gòu)建一個簡單的應(yīng)用程序。我遇到問題的組件是一個組件,它應(yīng)該通過映射以前通過從外部 API 獲取一些數(shù)據(jù)來填充的數(shù)組來呈現(xiàn)多個按鈕。這個數(shù)組填充在一個類方法中,結(jié)果最終被復(fù)制到另一個數(shù)組中,該數(shù)組是組件狀態(tài)的一部分當(dāng)我在組件的渲染方法上 console.log 數(shù)組的內(nèi)容時,一切看起來都很好。但是,如果我嘗試按索引打印特定元素,控制臺上會打印“未定義”。因此,地圖功能不會呈現(xiàn)所有所需的按鈕。我設(shè)法圍繞我填充數(shù)組的方式找到了不同的文檔,但到目前為止,沒有一篇文章表明我在做任何根本錯誤的事情。至少不是我能看到的。State 存儲一個空數(shù)組作為開始,并且在 componentWillMount 方法中調(diào)用 API 來獲取數(shù)據(jù)并更新數(shù)組,如下所示:this.state = {      resources: []}getAPIavaiableResources(api_resource) {    let buttonsArray = []    fetch(api_resource)      .then(response => response.json())      .then(data => {        for (let i in data) {          buttonsArray.push({id: i, name: i, url: data[i]})        }      }).catch(error => console.log(error))    this.setState({resources: buttonsArray})}componentWillMount() {    this.getAPIavaiableResources(ROOT_RESOURCE)}render() {    const { resources } = this.state;    console.log(resources)    console.log(resources[0])    return (      <div className="buttons-wrapper">        {          resources.map(resource => {            return <Button                      key={resource.id}                      text={resource.name}                       onClick={this.handleClick}                     />          })        }      </div>    )}這是在渲染方法上打印到控制臺上的內(nèi)容。[]0: {id: "people", name: "people", url: "https://swapi.co/api/people/"}1: {id: "planets", name: "planets", url: "https://swapi.co/api/planets/"}2: {id: "films", name: "films", url: "https://swapi.co/api/films/"}3: {id: "species", name: "species", url: "https://swapi.co/api/species/"}4: {id: "vehicles", name: "vehicles", url: "https://swapi.co/api/vehicles/"}5: {id: "starships", name: "starships", url: "https://swapi.co/api/starships/"}length: 6__proto__: Array(0)誰能看到我做錯了什么?我正在推送一個對象,因為我確實想要一個對象數(shù)組,盡管 Javascript 中的數(shù)組也是對象。任何幫助,將不勝感激。
查看完整描述

2 回答

?
森林海

TA貢獻2011條經(jīng)驗 獲得超2個贊

目前,您正在設(shè)置狀態(tài),而無需等待承諾得到解決。為此,請this.setState({resources: buttonsArray})在for循環(huán)后移動。


此外,您可以有條件地渲染組件,直到您通過執(zhí)行以下操作從遠程資源中獲得所需內(nèi)容:


render () {

  const { resources } = this.state;

  return resources.length

    ? (

      <div>Your content...</div>

    )

    : null // or some loader

}


查看完整回答
反對 回復(fù) 2021-06-03
  • 2 回答
  • 0 關(guān)注
  • 386 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號