映射数组项不会呈现所有元素

时间:2018-07-11 09:46:49

标签: javascript reactjs redux react-redux

更新对象中的答案后,它变得不确定。所以它不适合我的其余应用程序, 我在乞讨中所拥有的:

0
:
{answers: Array(5), category: {…}, description: null, legacyName: null, name: null, …}
1
:
{answers: Array(3), category: {…}, description: null, legacyName: null, name: null, …}
2
:
{answers: Array(3), category: {…}, description: null, legacyName: null, name: null, …}
3
:
{answers: Array(3), category: {…}, description: null, legacyName: null, name: null, …}
4
:
{answers: Array(2), category: {…}, description: null, legacyName: null, name: null, …}

更改后的内容:

0
:
undefined
1
:
undefined
2
:
undefined
3
:
undefined
4
:
undefined

减速器:

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

function updateItemInArray(array, questionId,answerId, newValue) {
  return {
    project: 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 project(state = [], action){

  switch(action.type){
    case 'PROJECT_FETCH_SUCCESS':
      return action.project; //initialize the project from a fetch
    case 'ANSWER_UPDATE_SUCCESS':
    {
      return updateItemInArray(state, action.questionId, action.answerId, action.newValue); //Want to change a value in one object in the array of arrays
    }
    default:
      return state
  }
}

我要做的是在数组中找到该数组,然后在该数组中找到对象以更改其值。但是由于某种原因,它返回未定义。我在redux文档中看到了正在使用的功能: https://redux.js.org/recipes/structuring-reducers/refactoring-reducers-example

1 个答案:

答案 0 :(得分:2)

您不是从map函数中的else条件返回

function updateItemInArray(array, questionId,answerId, newValue) {
  return {
    project: array.map(item => {
      if(item.id !== questionId) {
        return item;
      } else {
        // need a return statement here
        return item.answers.map(answer => {
          if(answer.id !== answerId) {
            return answer;
          } else {
            updateObject(answer, { value : newValue})
          }
        });
      }
    })
  }
}
相关问题