【问题标题】:Adding item 2 levels deep in Redux Reducer在 Redux Reducer 中添加 item 2 深度
【发布时间】:2019-08-12 22:30:04
【问题描述】:

我正在尝试向任务对象添加注释,但到目前为止我已经将它添加到所有任务中。当我尝试不同的方式时,它不会编译。 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
        })

【问题讨论】:

    标签: reactjs redux reducers


    【解决方案1】:

    您几乎从不想在 reducer 中使用 Array.push(),因为这会直接改变现有数组,并且直接突变通常会破坏 UI 更新(请参阅 Redux FAQ)。您可以在旧数组的新副本上使用push(),但大多数示例不使用这种方法。大多数情况下,建议的方法是使用const newArray = oldArray.concat(newValue),它返回一个包含所有旧项目和新项目的新数组引用。

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

    还没有实际测试过,但我认为您的代码需要大致类似于以下示例:

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

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 2020-12-05
      • 2020-09-06
      • 2017-11-03
      • 2018-03-31
      • 1970-01-01
      • 2023-03-09
      • 2021-03-03
      • 2017-07-12
      相关资源
      最近更新 更多