【问题标题】:Changing attribute in state React.js更改状态 React.js 中的属性
【发布时间】:2020-12-22 13:47:33
【问题描述】:

我正在用 React 做 Todo App,我需要一些帮助。这可能是一个微不足道的问题,但我不知道该怎么做。

context.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 时,我还想在 todos 数组中将其属性 important:false 更改为 important:true。目前,这段代码在不改变属性的情况下工作

todos: [...state.todos, { ...todos, important: true }],

行被删除。有了它,它只会复制所有的 todos,并将它们作为新的对象数组存储在 todos 数组中。我认为问题出在我的传播运算符上,因为我并不像我坚持的那样理解它们。

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

在addImportant案例中添加这个sn-p

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 2016-04-02
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多