2017-08-20 71 views
-2

在我的應用程序中,我從API中獲取數據並將其置於組件的狀態。如何設置數組中的特定項目?

this.state = { 
 
    contributors: [], 
 
} 
 

 
componentDidMount() { 
 
    axios.get(data) 
 
     .then(res => this.setState({contributors: res}) 
 
}

this.state.contributors是對象的數組。這些對象中的每一個都有3個屬性,其中有3個API調用的值。

0: { 
 
"name": "thisContributor", 
 
"followers_url": "https://api.github.com/users/thisContributor/followers", 
 
"gists_url": "https://api.github.com/users/thisContributor/gists", 
 
"repos_url": "https://api.github.com/users/thisContributor/repos", 
 
}

現在我需要遍歷,說100個貢獻者(或全部,但是這使得加載時間很長),並更新與響應的長度每個貢獻者。我想補充性質拿着這些長度:

0: { 
 
"name": "thisContributor", 
 
"followers_url": "https://api.github.com/users/thisContributor/followers", 
 
"gists_url": "https://api.github.com/users/thisContributor/gists", 
 
"repos_url": "https://api.github.com/users/thisContributor/repos", 
 
"followers": -length of followers_url API response-, 
 
"gists": -length of gists_url API response-, 
 
"repos": -length of repos_url API response- 
 
}

但是,這並不工作:

for (let i = 0; i < 100; i++) { 
 
    axios.get(`${this.state.contributors[i].followers_url}?per_page=100&${API_KEY}`) 
 
    .then(res => { 
 
    this.setState({contributors[i].followers: res.data.length}) 
 
    } 
 
}

如何解決這個問題,所以我可以更新關注者,要點和回購?

回答

0

試試這個

for (let i = 0; i < 100; i++) { 
    axios.get(`${this.state.contributors[i].followers_url}?per_page=100&${API_KEY}`) 
    .then(res => { 
    let tmp = [...this.state.contributors]; 
    tmp[i].followers = res.data.length 
    this.setState({contributors: tmp}) 
    } 
} 

更新:

fetch = (url, propertyName) => { 
    for (let i = 0; i < 100; i++) { 
     axios.get(url) 
     .then(res => { 
      let tmp = [...this.state.contributors]; 
      tmp[i][propertyName] = res.data.length 
      this.setState({contributors: tmp}) 
     } 
    } 
} 
... 
fetch(`${this.state.contributors[i].followers_url}?per_page=100&${API_KEY}`, "followers") 
fetch(`${this.state.contributors[i].gists_url}?per_page=100&${API_KEY}`, "gists") 
fetch(`${this.state.contributors[i].repos_url}?per_page=100&${API_KEY}`, "repos") 
+0

它的工作。非常感謝!一個問題:你會如何迴應這樣做的要點和回購,並保持代碼幹? –

+0

@AdamM檢查更新。可能這就是你要求的。 –

+0

當調用fetch()時,它返回一個錯誤 - '我沒有定義' –

0

我認爲這會解決您的問題。響應是一個對象,你用它來改變你的數組。而不是它,你可以在你的數組中推送響應。

componentDidMount() { 
    axios.get(data) 
     .then(res => this.setState((prevState)=>{contributors: [res, ...prevState.contributors]}) 
} 
相關問題