如何在数组中的特定项上设置State?

时间:2017-08-20 07:32:36

标签: javascript reactjs frontend

在我的应用中,我从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})
  }
}
&#13;
&#13;
&#13;

如何解决这个问题,以便我可以更新关注者,要点和回购?

2 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题。响应是一个对象,您可以使用它更改数组。您可以在阵列中推送响应,而不是它。

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

答案 1 :(得分: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")