【发布时间】:2021-11-04 07:22:56
【问题描述】:
这里先记录getNotes,然后记录updateNotes
有没有办法先updateNotes 然后getNotes?因为当我编辑并单击左箭头图标时,除非我刷新页面,否则它不会更新更改。
这是来自 NotesPage.js 的代码
const NotesPage = () => {
const [notes, setNotes] = useState([]);
useEffect(() => {
getNotes();
console.log('Log from getNotes');
}, [])
const getNotes = async () => {
const response = await fetch("http://localhost:5000/notes");
const data = await response.json()
setNotes(data)
}
这是来自 NotePage.js 的代码
function NotePage({ match, history }) {
const noteId = match.params.id;
const [note, setNote] = useState(null);
useEffect(() => {
getNote();
console.log("Log from getNote");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [noteId]);
const getNote = async () => {
if (noteId === 'new') return
const response = await fetch(`http://localhost:5000/notes/${noteId}`);
const data = await response.json();
setNote(data);
};
const updateNote = async () => {
await fetch(`http://localhost:5000/notes/${noteId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ ...note, "updated": new Date() }),
});
console.log("Log from updateNote");
};
const handeSubmit = () => {
if (noteId !== "new" && !note.body) {
deleteNote();
} else if (noteId !== "new") {
updateNote();
} else if (noteId === 'new' && note !== null) {
createNote()
}
history.push("/");
};
【问题讨论】:
标签: reactjs async-await react-hooks