简体   繁体   中英

In React redux state array of objects i can't update the state it creates error A state mutation was detected between dispatches

the component that dispatch the state

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

action

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

reducer

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;
  }
}
        

Sample data inside redux 在此处输入图片说明

the error am getting A state mutation was detected between dispatches, in the path personalInfoReducer.0.0.firstName . This may cause incorrect behavior.

您可以将每个对象分配到 Redux 中,并使用唯一的 Id 进行过滤,而不是更新对象数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM