我试图从 HTML 表单将数据从前端(React)发送到后端(express),并在提交后清除字段。这就是它的样子。这里 item 和 amount 是受控组件的状态。所以我的问题是我在获取状态之前更新状态而不是更新状态。由于 fetch 和 setState 是异步的,因此哪个将首先执行。即使我在 fetch 之后写入状态更新,似乎 fetch 也是首先执行的。但我不明白怎么办?
function onSub(e, setList, list) {
e.preventDefault();
setList([...list, { item, amount }]);
setItem("");
setAmt("");
fetch("http://localhost:3001/addData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ title: item, amt: amount }),
})
.then((res) => res.text())
.then((data) => {
console.log(data);
});
}
答案 0 :(得分:1)
他们在比赛。通常,您希望首先设置状态,因为状态设置器仅在 DOM 中本地运行,而 fetch
必须与服务器通信,但它们处于竞争状态,您不能看谁会赢得比赛。
如果你想控制哪个先发生,你需要明确地做到这一点。让 fetch
首先完成更容易,因为您可以等待调用状态设置器,直到 fetch
过程结束。这也让您有机会处理 fetch
故障(例如暂时性网络错误),而不会丢失用户提供的信息,因为您已将其从状态中清除:
function onSub(e, setList, list) {
e.preventDefault();
fetch("http://localhost:3001/addData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ title: item, amt: amount }),
})
.then((res) => {
if (!res.ok) { // This check was missing
throw new Error(`HTTP error ${res.status}`);
}
return res.text();
})
.then((data) => {
console.log(data);
setList([...list, { item, amount }]);
setItem("");
setAmt("");
})
.catch(error => {
setError(/*...some error message saying something went wrong...*/);
});
}
旁注:我解释了关于缺少 here 支票的评论。为了避免编写所有样板文件,我建议使用一些方便的实用程序函数,例如:
export async function postJSON(url, data) {
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!res.ok) { // This check was missing
throw new Error(`HTTP error ${res.status}`);
}
return res;
}
然后代码看起来像这样:
function onSub(e, setList, list) {
e.preventDefault();
postJSON("http://localhost:3001/addData", { title: item, amt: amount })
.then((data) => {
console.log(data);
setList([...list, { item, amount }]);
setItem("");
setAmt("");
})
.catch(error => {
setError(/*...some error message saying something went wrong...*/);
});
}