繁体   English   中英

在 state React.js 中更改属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM