【问题标题】:Mapping over array items doesn't render all elements映射数组项不会呈现所有元素
【发布时间】:2018-07-11 09:46:48
【问题描述】:

在我更新对象中的答案后,它变得未定义。所以它不适合我的应用程序的其余部分, 我在乞讨中得到了什么:

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

【问题讨论】:

  • return updateObject(answer, { value : newValue})

标签: javascript reactjs redux react-redux


【解决方案1】:

你不是从地图函数中的 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})
          }
        });
      }
    })
  }
}

【讨论】:

  • 谢谢老兄,这是我问题的答案,但我还需要将其与@The Reason 所做的评论结合起来
  • 这占用了我 5 个小时的生命,我所有的控制台日志都吐出了正确的信息,但是 concat 没有从我的比较结果中得到任何回报。谢谢@Shubham
猜你喜欢
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2017-07-03
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
相关资源
最近更新 更多