gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:17:30 24 4
gpt4 key购买 nike

我有数组存储 (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com