更新Redux存储区中对象数组元素的值

时间:2019-10-04 10:07:06

标签: redux react-redux

由动作创建者更新redux存储中json数组中的现有元素值存在挑战。 您也可以run code here在下面共享它;

console.clear()
const CreateTeam = (team, point) => {
  return {
    type:"CREATE_TEAM",
    payload: {team, point}
  }
}

const UpdateTeam = (team, point) => {
  return {
    type:"UPDATE_TEAM_POINT",
    payload: {team, point}
  }
}

const TeamReducer = (state = [], action) => {
  if(action.type == "CREATE_TEAM")
     {
      return [...state, action.payload]
     }
    if(action.type == "UPDATE_TEAM_POINT")
     {
       let point=action.payload.point;

      return [...state, {
        ...state.teams,
        point:point
      }]
     }
  return state;
}

const { createStore, combineReducers } = Redux;

const league = combineReducers({
  teams: TeamReducer
})

const store = createStore(league);

store.dispatch(CreateTeam("TeamA",10));
store.dispatch(CreateTeam("TeamB",20));

store.dispatch(UpdateTeam("TeamA",15));//not work
console.log(store.getState())

创建动作效果很好,我希望将TeamA的点值设置为15。.但是添加的新对象只有“点”属性值15

1 个答案:

答案 0 :(得分:1)

actionTypes名称错误:

  1. 动作调度type:"UPDATE_TEAM"
  2. 减速器处理action.type == "UPDATE_TEAM_POINT"

您必须执行不变的更改,请尝试以下操作:

const TeamReducer = (state = [], action) => {
  if(action.type == "CREATE_TEAM")
     {
      return [...state, action.payload]
     }
    if(action.type == "UPDATE_TEAM")
     {
       const {team, point} = action.payload;
       const changedIdx = state.findIndex((item) => item.team === team);
       return [...state.slice(0, changedIdx), action.payload, ...state.slice(changedIdx + 1)]

     }
  return state;
}