2017-02-25 63 views
0

如何在第二次获取使用第一次使用数据时获取链式异步操作?我需要获取仓库列表(GitHub API),然后从这些仓库中获取用户。我做了这个:如何使用存储中的数据获取动作(react-redux)

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。有什么建议么?

回答

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))); 
    }; 
} 
+0

谢谢了很多,它的作品! ;) – Alwox