[英]single reducer for multiple async calls in react ,redux
I am calling single post request multiple times like below from a component in React js:我从 React js 中的一个组件多次调用单个帖子请求,如下所示:
Object.keys(data).map(account => {
const accountRequest = {
accountNo: account.accountNo,
id : account.id
}
return this.props.requestAccountDetails(accountRequest)
}
requestAccountDetails is a function written in const mapDispatchToProps in container: requestAccountDetails 是容器中用 const mapDispatchToProps 编写的函数:
const mapDispatchToProps = (dispatch) => {
return {
requestAccountDetails : (accountDetails)=> {
dispatch(requestAccountDetailsInformation(accountDetails));
}
}
}
requestAcountDetailsInformation is an action written in action creator which calls redux-saga which is called multiple times asynchronously depending on no of accounts. requestAcountDetailsInformation 是在 action creator 中编写的 action,它调用 redux-saga,根据帐户数量异步调用多次。 So, if say number of accounts is 5 , post request I am calling is 5 times asynchronously using redux-saga.
因此,如果说帐户数为 5 ,则我调用的 post 请求是使用 redux-saga 异步调用的 5 次。
Issue is when my post request gets returned successfully, I am again calling success action which calls reducer and data is supplied to my component.But as the call is made 5 times and it is calling same success function and same reducer.It overwrites previous call result.问题是当我的 post 请求成功返回时,我再次调用调用 reducer 的成功操作,并将数据提供给我的组件。但是由于调用了 5 次,它调用了相同的成功函数和相同的 reducer。它覆盖了以前的调用结果。 Example: If my first request returns result, and second request returns result.My first request result is overwritten in reducer.
示例:如果我的第一个请求返回结果,第二个请求返回结果。我的第一个请求结果在减速器中被覆盖。
Can anyone help me how can I maintain result of all 5 requests in single reducer.任何人都可以帮助我如何在单个减速器中维护所有 5 个请求的结果。
you need to add result in array rather than overwrite in it.您需要在数组中添加结果而不是覆盖其中。 let say you have state.
假设你有状态。
const state = {
accountDetails =[]
}
In reducer in success call you can push new data in accountDetails and update state.在成功调用的减速器中,您可以在 accountDetails 中推送新数据并更新状态。
reducer(initialState=state, action)
switch(action.type){
....
case Authsuccess: return { ...initialState,
accountDetails : [
...initialState.accounDetails,
action.payload.accountInfo
],
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.