我保留一个名为";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的最佳布尔切换方法是什么?
您忘记返回.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.payload
获得减速器中的dene
。