【问题标题】:In React redux state array of objects i can't update the state it creates error A state mutation was detected between dispatches在 React redux 对象的状态数组中,我无法更新它创建的状态错误在调度之间检测到状态突变
【发布时间】:2020-09-13 08:56:37
【问题描述】:

分派状态的组件

const [personalInfo, setPersonalInfo] = useState([]);
dispatch(addPersonalInfo(personalInfo));

动作

import * as types from './actionTypes';
export default function addPersonalInfo(personalInfo) {
  return { type: types.ADD_PERSONAL_INFO, personalInfo };
}

减速器

import * as types from '../actions/actionTypes';

export default function personalInfoReducer(state = [], action) {
  debugger;
  switch (action.type) {
    case types.ADD_PERSONAL_INFO:
      return [...state, {...action.personalInfo}];
    case types.UPDATE_PERSONAL_INFO: {
      const newArray = [...state];
      const updatedArray = [
        ...newArray.filter((person) => person.id !== action.personalInfo.id),
        Object.assign({}, action.personalInfo),
      ];
      return [...state, {...updatedArray}];
    }

    default:
      return state;
  }
}
        

redux 中的示例数据

出现错误 在路径 personalInfoReducer.0.0.firstName 中检测到调度之间的状态突变。这可能会导致不正确的行为。

【问题讨论】:

  • 您所做的在概念上是错误的,状态可以是本地的或全局的,但不能同时是两者。如果您需要将 'personalInfo' 保持在全局状态,请移除 useState() 挂钩并从全局状态读取/写入 'personalInfo'(使用来自 react-reduxconnect() 将状态和操作映射到道具) .
  • 我看到 action.personalInfo 是一个数组,所以你做了 [..state, action.personalInfo] 并得到了 [[]] 结构。我看到personalInfor 应该是您添加到[] 中的对象。也许你应该改变const [personalInfo, setPersonalInfo] = useState({});
  • 现在我更新为对象数组

标签: javascript reactjs redux


【解决方案1】:

您可以将每个对象分派到具有唯一 ID 的 Redux 中进行过滤,而不是更新对象数组。

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 2017-11-04
    • 2017-04-24
    • 2018-11-03
    • 2019-10-13
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多