我使用(useReducer和useContext)制作待办事项,但更新功能不工作,请检查一下 &g



这是我的App.jsx,在这里我显示所有的待办事项,点击编辑后,输入得到所选的待办事项的值,而改变值并点击更新,它不做任何事情。

export default function App() {
const { dispatch, state } = useContext(todoContext);
const [todo, setTodo] = useState("");
const [isEditing, setIsEditing] = useState(false);
const [selectedTodo, setSelectedTodo] = useState("");
const handleSubmit = (e) => {
const id = uuidv4();
e.preventDefault();
if (!isEditing) {
dispatch({
type: "ADD_TODO",
payload: { id: id, text: todo },
});
setTodo("");
} else {
dispatch({
type: "UPDATE_TODO",
payload: selectedTodo,
});
setIsEditing(false);
setTodo("");
}
};
const handleEdit = (val) => {
setIsEditing(true);
const item = state.todos.find((todo) => todo.id === val.id);
setTodo(item.text);
setSelectedTodo(item);
};
return (
<div className="App">
<br />
<h1>Hello World This is Todo App</h1>
<br />
<form onSubmit={handleSubmit}>
<input
value={todo}
onChange={(e) => setTodo(e.target.value)}
type="text"
placeholder="Enter a todo"
/>
<button>{isEditing ? "Update" : "Submit"}</button>
</form>
{state.todos.map((item) => (
<div key={item.id} className="todoitem">
<p
onClick={() => dispatch({ type: "TOGGLE_TODO", payload: item.id })}
style={{
cursor: "pointer",
textDecoration: item.completed ? "line-through" : "",
}}
>
{item.text}
</p>
<span
onClick={() => dispatch({ type: "REMOVE_TODO", payload: item.id })}
>
&times;
</span>
<button onClick={() => handleEdit(item)}>Edit</button>
</div>
))}
</div>
);
}

这是我的reducers (todoreducers .jsx),其中的更新功能不工作,当我点击编辑改变值,点击更新它不做任何

export const INITIAL_STATE = {
todos: [],
updated: [],
};
export const reducer = (state, action) => {
switch (action.type) {
case "ADD_TODO":
return {
...state,
todos: [...state.todos, action.payload],
};
case "REMOVE_TODO": {
return {
...state,
todos: state.todos.filter((item) => item.id !== action.payload),
};
}
case "TOGGLE_TODO":
return {
...state,
todos: state.todos.map((todo) =>
todo.id === action.payload
? { ...todo, completed: !todo.completed }
: todo
),
};
case "UPDATE_TODO":
return {
...state,
todos: state.todos.map((todo) => {
if (todo.id === action.payload.id) {
return action.payload;
}
return todo;
}),
};
default:
return state;
}
};

你需要用最新的文本更新文本

  • selectedTodo有旧数据
  • 有新文本

在你的handlessubmit请更新以下代码

dispatch({
type: "UPDATE_TODO",
payload: { ...selectedTodo, text: todo },
});

最新更新