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

标签 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

reducer :

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

最佳答案

您没有从 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})
          }
        });
      }
    })
  }
}

关于javascript - 映射数组项不会呈现所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51282291/

相关文章:

javascript - 如何以有效的方式向 HTML 元素添加属性?

javascript - 如何阻止背景样式覆盖 React 内联样式的 backgroundColor 样式?

redux - TypeError : Object(. ..) 不是函数(redux)

javascript - 更新表单中的数据。保持可编辑状态。 (与 Redux react ,无 redux-form)

javascript - 在react+redux应用程序的Home组件中,在componentdidmount上调用action getPosts()后,this.props.posts未定义

JavaScript "Maximum Call Size Stack Exceeded"

javascript - 当我将属性作为字符串插入时,如何防止 Angular 进行数学运算

javascript - V8 引擎是否使用 C++ 替换了以前用 JavaScript 编写的部分代码库?

javascript - 无法使用父级传递的值在子组件内设置状态

javascript - TypeError : this. props.match 在组件中未定义