javascript - 如何在reducer中的数组索引处添加对象

标签 javascript arrays redux react-redux redux-store

我有数组存储 (store.calendar[0].todos[{title: title, etc...}])

    0: {todos: Array(0)}
    1: {todos: Array(0)}
    2: {todos: Array(0)}
    3: {todos: Array(0)}
    4: {todos: Array(0)}

我需要将操作对象添加到数组的索引待办事项中: 我试过使用这个 reducer ,但出现错误:

state.calendar[newTodo.day].concat is not a function

我的 reducer :

let initialState = { calendar: []}

for (let i = 1; i <= 30; i++) {
  initialState.calendar.push({ todos: []});
}

const todosReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TODO:
      const newTodo = action.todoItem;
      const newStore = {...state,
            todos: state.calendar[newTodo.day].concat(newTodo)};
      return newStore;
    default:
      return state
  }
}

export default todosReducer;

我的行动:

export const addTodoAction = (todoItem) => {
  return {
    type: ADD_TODO,
    todoItem
  }
}

我的添加待办事项功能:

const handleSaveTodo = () => {
    props.addTodo({ 
      day: 5,
      title: trackInput.value,
      description: trackTextarea.value,
      completed: false
    });
}

最佳答案

您需要以完全不可变的方式更改您的状态。

为此,您必须复制日历数组、您在此日历中更新的日期以及您要附加到的待办事项列表。

首先获取daytodoItem,可以使用解构:

const { todoItem } = action;
const { day } = todoItem;

然后复制你的日历,你可以使用传播语法:

const calendar = [...state.calendar];

然后用当天的副本更新相关日期,并将新的待办事项附加到待办事项列表中:

calendar[day] = { ...calendar[day], todos: [...calendar[day].todos, todoItem] };

然后返回更新后的状态:

return { ...state, calendar };

举个例子:

const ADD_TODO = 'add-todo';

const initialState = { calendar: Array.from({ length: 30 }, (_, i) => ({ todos: [] })) };

const todosReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TODO:
      const { todoItem } = action;
      const { day } = todoItem;
      const calendar = [...state.calendar];
      calendar[day] = { ...calendar[day], todos: [...calendar[day].todos, todoItem] };
      return { ...state, calendar };
    default:
      return state
  }
}

let state = initialState;

state = todosReducer(state, { type: ADD_TODO, todoItem: { day: 0, title: 'todo day 1' } });
state = todosReducer(state, { type: ADD_TODO, todoItem: { day: 1, title: 'todo day 2' } });
state = todosReducer(state, { type: ADD_TODO, todoItem: { day: 2, title: 'todo day 3' } });
state = todosReducer(state, { type: ADD_TODO, todoItem: { day: 2, title: 'second todo day 3' } });

console.log(state.calendar.slice(0, 3));

关于javascript - 如何在reducer中的数组索引处添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269753/

相关文章:

javascript - 这里的 input 如何获得 .value 以及什么是 ref?

javascript - innerHTML 不写入 svg 组 Firefox 和 IE

JavaScript 错误 : SyntaxError: return not in function on line 22

javascript - 为什么暂停图标未在JS中显示

JavaScript 转换日期

c++ - 所有数的最大公约数之和,直到 n 与 n

c - 使用指针反转字符串

javascript - Selenium 二维数组

javascript - 如何根据AJAX调用设置ReduxReducer的初始状态?

javascript - TypeError : _this. store.getState 不是从 Redux 使用连接时的函数