如何在redux react.js的reducer函数中进行多重分配和添加操作? 更新

问题描述

我正在开发一个使用 redux 进行状态管理的 react 应用程序,我是新手,我必须在 reducer 函数中执行多个状态更改操作。

这是我的减速器功能

case Actions.ON_SUBMIT_CLIENT: {
  return {
    ...state,clientList: [...state.clientList,action.client]
  }
}

我想要做的是,将一个项目添加clientList,我在这里做的然后重新分配 2 个变量 clientNameclientStatus 太像:

case Actions.ON_SUBMIT_CLIENT: {
  return {
    ...state,action.client],clientName: "",clientStatus: "",clientAccessGrants: []
  }
} 

如何在reducer函数中实现这一点? 任何帮助将不胜感激。

这是我的 github 链接here

您可以在 clientReducer 中看到 reducer,在 Form/PopupActions 中看到 ON_SUBMIT 操作调用

解决方法

问题

您已经声明了外部返回值。

https://github.com/Himanshuranjan30/ClientDash2/blob/master/src/clientDashboard/actions/clientReducer.js#L269-L278

case Actions.ON_SUBMIT_CLIENT:{
  clientName:""; // <-- not returned
  clientStatus:""; // <-- not returned
  clientAccessGrants:[] // <-- not returned
  return {
    ...state,clientList: [...state.clientList,action.client],}
}

解决方案

如果您想更新状态,它们需要作为从 reducer 案例返回的 next 状态值的一部分返回。

case Actions.ON_SUBMIT_CLIENT:
  return {
    ...state,clientName: "";
    clientStatus: "";
    clientAccessGrants: [];
  }

更新

所以看起来你要么调度了错误的动作,要么在减速器中处理了错误的动作。

submitClient 动作创建者分派 Actions.SUBIMT_CLIENT ('CLIENT/SUBIMT_CLIENT') 类型的动作,但您的 reducer 案例正在处理 Actions.ON_SUBMIT_CLIENT 类型的动作 ({{1} })。动作创建器中“提交”的拼写有误,因此很难追踪。

更新 reducer 以处理现在分派的相同动作类型会清除/重置其他状态。

'Actions.ON_SUBMIT_CLIENT'

这是一个 codesandbox fork of your github repo。我添加了 redux 开发工具,所以如果你有扩展,你可以看到它们被分派时的动作并检查状态差异。

enter image description here

,

如果 clientName 和 clientStatus 在 cleintList 之外 你可以使用这个代码

case Actions.ON_SUBMIT_CLIENT: {
  return {
    ...state,clientName: [...state.clientName,action.clientName],clientStatus: [...state.clientStatus,action.clientStatus],clientAccessGrants: [...state.clientAccessGrants,action.clientAccessGrants]
  }
} 

但是如果没有 你可以使用这个代码

case Actions.ON_SUBMIT_CLIENT:{
state.clientList.clinetName=action.client.clientName
state.clientList. clientStatus =action.client. clientStatus
          return {
            ...state,action.client]
          }
        }
,

将 clientName 和 Client Status 添加到您的 Reducer 初始状态中也像

const initialState = {
  clientList: [],clientName: '',clientStatue: ''
}

export default function reducerName(state= initialState,action) {
  switch(action.type) {
    case ON_SUBMIT_CLIENT:
      return {
        ...state,clientName:"",clientStatus:"",clientAccessGrants:[]
      }
  }
}