簡體   English   中英

為什么這不改變我的redux狀態?

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

我的狀態中有一個對象數組。 我想做的是找到具有正確ID的問題,然后找到具有正確ID的答案以更改其值並將其更新為狀態。

這是我得到的:

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

我正在看的物體有點明顯,但是看起來像這樣

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

和其他一些屬性,但這與這個問題無關。 感謝每一個答案!

您需要在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