【问题标题】:Why redux toolkit boolean toggle doesn't work?为什么 redux 工具包布尔切换不起作用?
【发布时间】:2021-09-14 08:30:26
【问题描述】:

我保留了一个名为“isCompleted”的布尔值,但它不起作用。为假时为真,但之后不再为假。我写的 Redux 动作和函数如下。这可能是什么原因?感谢您的提前。

const todoSlice = createSlice({
    name: 'todos',
    initialState: {
        todos: []
    },
    reducers: {
        addTodo: (state, action) => {
            state.todos = [...state.todos, action.payload]
        },
        deleteTodo: (state, action) => {
            state.todos = action.payload
        },
        completedTodo: (state, action) => {
            state.todos = action.payload
        }
    }
})

export const {
    addTodo,
    deleteTodo,
    completedTodo
} = todoSlice.actions

export const selectUser = (state) => state.todos;

export const store = configureStore({
    reducer: todoSlice.reducer
})
const Todo = () => {
    const user = useSelector(selectUser);
    const dispatch = useDispatch();

    const checkHandler = (id) => {
        const dene = user.map((item) => {
            if (item.id === id) {
                const comp = item.isCompleted
                return {
                    ...item,
                    isCompleted: !item.isCompleted
                };
            }
        })
        dispatch(completedTodo({dene}))
    }

    const deleteHandler = (id) => {
        const filteredTodos = user.filter(todo => todo.id !== id)
        dispatch(deleteTodo(filteredTodos))
    }

    return (
        user.map((todo) => {
            return <li key={todo.id} className={todo.isChechked ? "todo-item checked" : "todo-item"}>
                <p>{todo.title}</p>
                <div className="btns">
                    <IconButton onClick={() => deleteHandler(todo.id)} className="trash-btn" aria-label="delete">
                        <DeleteIcon />
                    </IconButton>
                    <IconButton onClick={() => checkHandler(todo.id)} className="complete-btn" aria-label="delete">
                        <CheckIcon />
                    </IconButton>
                </div>
            </li>
        })
    )
}

export default Todo

Redux 最好的布尔切换方法是什么?

【问题讨论】:

    标签: reactjs redux react-redux redux-toolkit


    【解决方案1】:

    您忘记返回 .map() 函数中的其他 todo 项目。会导致state.todos不正确。

    const dene = user.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          isCompleted: !item.isCompleted,
        };
      }
      // notice here
      return item;
    });
    
    dispatch(completedTodo(dene));
    

    直接将dene传递给action creator,你可以从action.payload获取reducer中的dene

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 2022-12-07
      • 2022-09-29
      • 1970-01-01
      相关资源
      最近更新 更多