我正在学习React JS,并尝试创建一个CRUD应用程序。在表单中,我可以成功地获取现有数据并绑定到表单控件。但是,输入框的onchange事件似乎没有更新相应的状态。分享代码示例。任何输入都非常感谢。
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { useNavigate } from "react-router-dom";
function BookEdits() {
const navigate = useNavigate();
const [data, setData] = useState("");
const [title, setTitle] = useState("");
const params = useParams();
// Please ignore this part
const handleSubmit = (event) => {
event.preventDefault();
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: title,
description: description,
author: author,
}),
};
fetch(`https://localhost:7174/api/books/${params.id}`, requestOptions).then(
(response) => {
console.log(response);
if (!response.ok) alert("Error saving book details");
else alert("Book details is saved successfully");
navigate("/BooksList");
}
);
};
//
useEffect(() => {
fetch(`https://localhost:7174/api/Books/${params.id}`)
.then((response) => response.json())
.then(setData);
}, []);
// Does not change post onchange event
console.log(data.title);
return (
<form onSubmit={handleSubmit}>
<label>
Title:
<input type="submit" />
</form>
);
<input
type="text" value={data.title}
onChange={(e) => setTitle(e.target.value)}
/>
</label>
<input type="submit" />
</form>
);
}
export default BookEdits;
状态应该更新post onchange事件。我在这里错过了什么?提前感谢。
1条答案
按热度按时间rryofs0p1#
data.title
与title
不同,您调用了setTitle
,它更改了title
,但您记录的是data.title
,这不是相同的属性。