Pan*_*ool 2 arrays object reactjs redux react-redux
我正在尝试使用 redux 制作一个待办事项应用程序,我正在讨论如何从数组中删除一个待办事项。
减速器.js
export default function todo(state, action) {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
id: action.id,
text: action.text,
completed: false
}
case 'REMOVE_TODO':
return {
id: action.id,
...state.slice(id, 1)
}
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
动作.js
let nextTodoId = 0
export const addTodo = text => ({
type: 'ADD_TODO',
id: nextTodoId++,
text
})
export const removeTodo = id => {
type: 'REMOVE_TODO',
id
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我可以添加和切换待办事项是否已完成。谢谢
使用 redux 您需要返回所有数组元素,除了从 reducer 中删除的元素。
就个人而言,我更喜欢使用filterArray的方法。它会返回一个state匹配特定条件的数组的浅拷贝。
case 'REMOVE_TODO':
return state.filter(({id}) => id !== action.id);
Run Code Online (Sandbox Code Playgroud)