在我的應用程序中,我從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})
}
}
如何解決這個問題,所以我可以更新關注者,要點和回購?
它的工作。非常感謝!一個問題:你會如何迴應這樣做的要點和回購,並保持代碼幹? –
@AdamM檢查更新。可能這就是你要求的。 –
當調用fetch()時,它返回一個錯誤 - '我沒有定義' –