如何在获取操作中使用存储中的数据(react-redux)
How use data from store in fetch action (react-redux)
如何在第二次获取使用第一次获取的数据时进行获取链异步操作?我需要获取存储库列表 (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
。有什么建议吗?
假设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)));
};
}
如何在第二次获取使用第一次获取的数据时进行获取链异步操作?我需要获取存储库列表 (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
。有什么建议吗?
假设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)));
};
}