【问题标题】:single reducer for multiple async calls in react ,redux用于反应中多个异步调用的单个减速器,redux
【发布时间】:2021-01-13 05:40:11
【问题描述】:

我从 React js 中的一个组件多次调用单个发布请求,如下所示:

Object.keys(data).map(account => {
    const accountRequest = {
        accountNo: account.accountNo,
        id : account.id
    }
    return this.props.requestAccountDetails(accountRequest)
}

requestAccountDetails 是容器中用 const mapDispatchToProps 编写的函数:

const mapDispatchToProps = (dispatch)  => {
    return {
        requestAccountDetails : (accountDetails)=> {
            dispatch(requestAccountDetailsInformation(accountDetails));
        }
    }
}

requestAcountDetailsInformation 是一个用 action creator 编写的 action,它调用 redux-saga,它会根据账户的数量异步调用多次。因此,如果说帐户数是 5 ,我正在调用的 post 请求是使用 redux-saga 异步调用的 5 次。

问题是当我的 post 请求成功返回时,我再次调用调用 reducer 的成功操作并将数据提供给我的组件。但是由于调用了 5 次,它正在调用相同的成功函数和相同的 reducer。它覆盖之前的调用结果。示例:如果我的第一个请求返回结果,第二个请求返回结果。我的第一个请求结果在 reducer 中被覆盖。

谁能帮助我如何在单个减速器中维护所有 5 个请求的结果。

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-saga


    【解决方案1】:

    您需要在数组中添加结果而不是在其中覆盖。 假设你有状态。

    const state = {
    accountDetails =[]
    }
    

    在成功调用的 reducer 中,您可以在 accountDetails 中推送新数据并更新状态。

      reducer(initialState=state, action)
        switch(action.type){
          ....
        case Authsuccess: return { ...initialState,
                                    accountDetails : [ 
                                    ...initialState.accounDetails, 
                                     action.payload.accountInfo
                                     ],
                                  }
               
    
                                      
    

    【讨论】:

    • 但是 accountDetails =[] 在每次调用时都会被初始化为 []
    • 不,我们已经在 initialState 中初始化过一次数组。在成功调用时,我们会将先前存储的结果附加到 accountDetails 和新的有效负载数据中。
    • 如果不是这种情况,请提供更多详细信息,似乎状态在每次成功调用中都变空了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2022-06-29
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多