[英]Changing attribute in state React.js
我正在 React 中做 Todo App,我需要一些幫助。 這可能是一個微不足道的問題,但我不知道該怎么做。
上下文.js:
const initialState = {
isSidebarOpen: true,
isLoading: false,
isEditing: false,
todos: [
{ id: 1608592490852, todo: "Buy milk", important: false },
{ id: 1608592490939, todo: "Take out trash", important: false },
{ id: 1608634291740, todo: "Buy flowers for mom", important: false },
{ id: 1608634291874, todo: "Repair washing machine", important: false },
],
importantTodos: [{ id: 1608634291874, todo: "Repair washing machine" }],};
const handleAction = (e, item) => {
const { id, todo } = item;
const actionName = e.target.getAttribute("name");
if (actionName === actionTypes.addImportant) {
dispatch({ type: actionTypes.addImportant, payload: id });
}
reducer.js:
const reducer = (state, action) => {
const { todos } = state;
switch (action.type) {
case actionTypes.addTodo:
return {
...state,
todos: [...state.todos, { id: action.payload.id, todo: action.payload.todo, important: false }],
};
case actionTypes.addImportant:
const importantTodo = todos.find((item) => item.id === action.payload);
console.log(state);
return {
...state,
todos: [...state.todos, { ...todos, important: true }],
importantTodos: [...state.importantTodos, { id: importantTodo.id, todo: importantTodo.todo }],
};
default:
throw new Error(`No Matching "${action.type}" - action type`);
}};
將 ToDo 添加到 importantTodos 時,我還想將其屬性 important:false 更改為 important: true in todos 數組。 目前,此代碼在不更改屬性的情況下工作
todos: [...state.todos, { ...todos, important: true }],
行被刪除。 它只是復制所有待辦事項,並將它們作為新的對象數組存儲在待辦事項數組中。 我認為問題出在我的差價操作員身上,因為我並不像我認為的那樣理解它們。
在 addImportant 案例中添加此代碼段
const updatedTodos = todos.map(todoEl => {
if(todoEl.id === action.payload){
const {id, todo} = todoEl;
return {id, todo, important: true}
}
return todoEl;
})
更新退貨聲明:
return {
...state,
todos: updatedTodos,
importantTodos: [...state.importantTodos, { id: importantTodo.id, todo: importantTodo.todo }],
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.