【问题标题】:Updating state with nested array of objects使用嵌套的对象数组更新状态
【发布时间】:2017-10-12 03:12:06
【问题描述】:

这也称为深度状态更新。我必须更新嵌套状态数组。

我正在实现一个简单的 redux 应用程序。在这里,我想更新嵌套对象数组的状态。我的减速器功能需要状态,动作。我必须用新值更新状态的响应属性。我试图映射/迭代状态,但它不适合我。有没有办法更新这些特定值并返回更新状态。

const sampleData = [{
  "id": 1,
  "text": "Hobby",
  "answers": [{
    "id": 1,
    "text": "Chess",
    "responses": 5
  }]
}];

const action = {
  type: "VOTE",
  questionId: 1,
  answerId: 3
};

这是我在表单上单击提交按钮时调用的 handleSubmit 函数。

handleSubmit(e){
  const store = createStore(hobbyReducer, hobby); // created store here
  var k = (document.querySelector('input[name = "hobby"]:checked').value);

  store.dispatch({type:"SUBMIT", text: k, id: 1});  // Dispatching action to reducer
  store.subscribe(()=>{

      console.log(store.getState());
  });
}

这是程序的reducer部分:

function hobbyReducer(state, action) {
    switch(action.type){
      case "SUBMIT":
            return{
              ...state,
              answers: state.answers.map(e=> (e.text === action.text && e.answers.id === action.id)?
              { ...answers, 
              responses: (e.responses+1)} :
             hobby )
          }
      break;
      default:
        return state;
    }
}

初始状态 = sampleData; // 上面给出的数组对象

我无法更新嵌套数组中的响应属性

这是我想写的代码,经过一番研究,我终于做到了。虽然这不是时间复杂度的解决方案。

`

case "SUBMIT":
        const updatedState = state.map(e =>{
          if(e.id === action.id)
            return{...e,
                  answers: e.answers.map(f =>{
              if(f.text === action.text){
                return{
                  ...f,
                  ...{responses: f.responses + 1},

                }
              }
              return f;
            })
          }
        return e;
        })
        console.log("updatedstate", updatedState)
        return updatedState

【问题讨论】:

  • 请提供状态的上一个和下一个值,您正在使用的reducer以及用于状态转换的操作。
  • @palsrealm 请检查我是否更新了信息

标签: arrays reactjs redux


【解决方案1】:

我认为只是你的地图中的一个错误:

 function hobbyReducer(state, action) {
    switch(action.type) {
      case "SUBMIT":
        return {
          ...state,
          answers: state.answers.map(answer => {
            if (answer.text === action.text && answer.id === action.id) {
              answer.response = answer.response + 1;
            }
            return answer;
          });
        }
      default:
        return state;
    }
}

【讨论】:

  • 这应该可以,但看起来我的 redux 状态操作有问题。我会去的,谢谢。
  • 我已经用我想为 redux 中的嵌套状态对象实现的新代码和实际代码更新了我的帖子。
  • 您在 state 上调用 map,就好像它是一个数组一样,但 state 是一个对象。您对我的回答有什么具体问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2021-12-23
  • 2019-08-28
  • 2019-06-13
  • 2018-07-04
  • 2020-12-08
  • 2017-04-30
相关资源
最近更新 更多