如何使用存储中的数据进行获取操作(react-redux)

时间:2017-02-25 15:46:26

标签: redux fetch

如何在第二次获取第一次使用数据的情况下进行获取链异步操作?我需要获取存储库列表(GitHub API),然后从这些存储库中获取用户。我做了这个:

export function reposListFetchData(url) {
  return (dispatch) => {
    dispatch(reposListIsLoading(true))

    fetch(url)
      .then((response) => {
        if(!response.ok){
          throw Error(response.statusText)
        }

        dispatch(reposListIsLoading(false))

        return response
      })
      .then((response) => response.json())
      .then((repos) => dispatch(reposListFetchSuccess(repos)))
      .then( this.props.repos.map(
  repo=>this.props.fetchContributorsData(`https://api.github.com/repos/angular/${repo.name}/contributors?per_page=100`)
      ))
     .catch(()=> dispatch(reposListHasErrored(true)))
   }
}

但当然我不能在那里使用this.props。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

假设fetchContributorsData是一个与reposListFetchData非常相似的动作,你应该可以这样做......

export function reposListFetchData(url) {
  return dispatch => {
    dispatch(reposListIsLoading(true));
    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw Error(response.statusText);
        }
        dispatch(reposListIsLoading(false));
        return response;
      })
      .then(response => response.json())
      .then(repos => {
        dispatch(reposListFetchSuccess(repos));
        // where repos is an array of repo
        repos.map(repo =>
          dispatch(fetchContributorsData(`https://api.github.com/repos/angular/${repo.name}/contributors?per_page=100`))
        );
      })
      .catch(() => dispatch(reposListHasErrored(true)));
  };
}