我正在用純 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ù)組也是對象。任何幫助,將不勝感激。
訪問 JavaScript 數(shù)組返回“未定義”
白衣非少年
2021-05-31 18:04:05