在Redux Reducer中深入添加第2项级别

时间:2016-06-24 18:43:34

标签: reactjs redux reducers

我正在尝试向任务对象添加注释,但到目前为止我已将其添加到所有任务中。当我尝试不同的方式时,它不会编译。 Object.assign并不喜欢来自.push()

当它添加到所有任务时:

 let taskReducer = function(tasks = [], action) {
  switch (action.type) {
    case 'ADD_NOTE':
      return tasks.map((task) => {
        const { notes } = task;
        const { text } = action;
        notes.push({
           text,
           id: notes.length,
         })
          return task.id === action.id ?
            Object.assign({}, { task, notes }) : task
        })

当它没有编译时:

let taskReducer = function(tasks = [], action) {
  switch (action.type) {
    case 'ADD_NOTE':
      return tasks.map((task) => {
       return task.id === action.id ?
        const { notes } = task;
        const { text } = action;
        notes.push({
           text,
           id: notes.length,
         })
           Object.assign({}, { task, notes }) : task
        })

1 个答案:

答案 0 :(得分:1)

您几乎不想在reducer中使用Array.push(),因为这会直接改变现有数组,而直接突变通常会破坏UI更新(请参阅http://redux.js.org/docs/FAQ.html#react-not-rerendering)。您可能旧数组的新副本上使用push(),但大多数示例都不使用该方法。大多数情况下,建议的方法是使用const newArray = oldArray.concat(newValue),它返回一个包含所有旧项目和新项目的新数组引用。

除此之外,请记住,在不可更新地更新嵌套数据时,每个级别的嵌套都需要制作并返回一个副本。

Haven实际上已对此进行了测试,但我认为您的代码需要大致如下所示:

let taskReducer = function(tasks = [], action) {
    switch (action.type) {
        case 'ADD_NOTE':
            return tasks.map((task) => {
                if(action.id !== task.id) {
                    return task;
                }

                const { notes } = task;
                const { text } = action;
                const newNotes = notes.concat({id : notes.length, text});

                const newTask = Object.assign({}, task, {notes : newNotes});

                return newTask;
            }
        default : return tasks;
    }
}
相关问题