我保留了一个名为“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 最好的布尔切换方法是什么?
答案 0 :(得分:0)
您忘记返回 todo
函数中的其他 .map()
项。它会导致 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,可以从dene
获取reducer中的action.payload
。