如何在 redux react.js 中的 reducer 函数中进行多次赋值和添加操作?

How to do muliple assign and add operations in reducer function in redux react.js?

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

这是我的减速器函数:

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

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

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

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

这是我的 github link:here

你可以在clientReducer中看到reducer,Form/PopupActions中的ON_SUBMIT动作调用。

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

case Actions.ON_SUBMIT_CLIENT: {
  return {
    ...state,
    clientList: [...state.clientList, action.client],
    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,
            clientList: [...state.clientList, 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,
        clientList: [...state.clientList, action.client],
        clientName:"",
        clientStatus:"",
        clientAccessGrants:[]
      }
  }
}

问题

您已在 之外声明了值 return。

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],
    
  }
}

解决方案

如果您想更新状态,需要将它们 returned 作为 next 状态值的一部分 return来自于减速器案例。

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

更新

看来你在 reducer 中发送了错误的动作或处理了错误的动作。

submitClient 动作创建者调度了一个类型为 Actions.SUBIMT_CLIENT 的动作('CLIENT/SUBIMT_CLIENT'),但是你的 reducer 案例正在处理一个类型为 Actions.ON_SUBMIT_CLIENT 的动作('Actions.ON_SUBMIT_CLIENT').动作创建器中“提交”的拼写有错,所以这个很难追踪。

更新减速器以处理现在分派的相同动作类型clears/resets其他状态。

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

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