简体   繁体   English

为什么这不改变我的redux状态?

[英]Why doesn't this change my redux state?

I have an array of array of objects in my state. 我的状态中有一个对象数组。 What I want to do is find the question with the correct id, then find the answer with the correct id to change it's value and update it to the state. 我想做的是找到具有正确ID的问题,然后找到具有正确ID的答案以更改其值并将其更新为状态。

Here is what I got: 这是我得到的:

function updateObject(oldObject, newValues) {
  return Object.assign({}, oldObject, newValues);
}

function updateItemInArray(array, questionId,answerId, updateItemCallback) {
  const getQuestion = array.map(item => {
    if(item.id !== questionId) {
      return item;
    }
  })
  const updatedItem = getQuestion[0].answers.map(answer => {
    if(answer.id !== answerId) {
      return answer;
    }
​
    const updatedItem = updateItemCallback(answer);
    return updatedItem;

  });
​
  return updatedItems;
}



export function answerUpdate(state = [], action){
  switch(action.type){
    case 'ANSWER_UPDATE_FETCH_SUCCESS': {
      const newAnswer = updateItemInArray(state.project, action.questionId, action.answerId, answer => {
        return updateObject(answer, {value : action.newValue});
      });
    }
  }
}

the object I'm looking through is kinda obvious but it looks something like this 我正在看的物体有点明显,但是看起来像这样

project = [
  question = {
    id:"some Id",
    answers:  [
    {
      id:"another id",
      value="someValue"
    }
    ]
  }
]

and some other properties but it is unrelevant for this question. 和其他一些属性,但这与这个问题无关。 Thankful for every answer! 感谢每一个答案!

You need to update data in map itself instead of creating variable, map function returns new array with updated value and you are updating 0th index of array which won't be one you're looking for. 您需要在map本身中更新数据而不是创建变量,map函数将返回具有更新值的新数组,并且您正在更新数组的第0个索引,而该索引将不是您要查找的索引。

function updateItemInArray(array, questionId,answerId, newValue) {
  return array.map(item => {
      if(item.id !== questionId) {
        return item;
      } else {
        item.answers.map(answer => {
          if(answer.id !== answerId) {
            return answer;
          } else {
            updateObject(answer, { value : newValue})
          }
        });
      }
    });
}

export function answerUpdate(state = [], action){
  switch(action.type){
    case 'ANSWER_UPDATE_FETCH_SUCCESS': {
      return updateItemInArray(state, action.questionId, action.answerId, action.newValue);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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