簡體   English   中英

訪問JavaScript數組返回“未定義”

[英]Accessing JavaScript Array returns “undefined”

我正在用純Reactjs構建一個簡單的應用程序。 我遇到問題的組件是應該通過映射一個以前通過從外部API提取一些數據來填充的數組來呈現許多按鈕的組件。 此數組填充在類方法中,結果最終復制到另一個數組中,該數組是組件狀態的一部分

當我用console.log在組件的render方法上記錄數組的內容時,一切看起來都很好。 但是,如果我嘗試通過其索引打印特定元素,則控制台上會打印“ undefined”。 結果,地圖功能無法呈現所有所需的按鈕。

在填充數組的方式上,我設法找到了不同的文檔,但是到目前為止,沒有一篇文章表明我在做任何根本上錯誤的事情。 至少我看不到。

State存儲一個空數組,以componentWillMount方法開頭,並在componentWillMount方法內調用一個API,該API會按以下所述獲取數據並更新該數組:

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>
    )
}

這就是在render方法上打印到控制台上的內容。

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

誰能看到我在做什么錯? 我要推送一個對象是因為我確實想要一個對象數組,盡管Javascript中的數組也是對象。 任何幫助,將不勝感激。

當前的實現方式是在獲取數據之前先設置狀態,然后在api調用返回后再更改狀態。 React無法分辨您何時進行更改,因此不知道要重新渲染。 僅當您調用setState(或當它收到新的道具)時,它才知道要重新渲染。

相反,請等到擁有數據,然后再使用填充的數組調用setState。

getAPIavaiableResources(api_resource) {
  fetch(api_resource)
    .then(response => response.json())
    .then(data => {
      let buttonsArray = []
      for (let i in data) {
        buttonsArray.push({id: i, name: i, url: data[i]})
      }
      this.setState({resources: buttonsArray})
    }).catch(error => console.log(error))
}

componentDidMount() {
    this.getAPIavaiableResources(ROOT_RESOURCE)
}

上面的示例還更新了代碼,以使用componentDidMount而不是componentWillMount。 componentWillMount已棄用,無論如何都不打算用於這種情況。

當前,您正在設置狀態,而無需等待承諾被解決。 為此,請在for循環后移動this.setState({resources: buttonsArray})

另外,您可以有條件地渲染組件,直到通過執行以下操作從遠程資源獲得所需的內容:

render () {
  const { resources } = this.state;
  return resources.length
    ? (
      <div>Your content...</div>
    )
    : null // or some loader
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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