javascript - 如何渲染使用表单输入添加的数据?
问题描述
我正在从 API 呈现信息,但我还需要呈现使用 webform 添加的新信息。我制作了这个表单来添加简单的信息作为来自 API 的对象。如何在此处呈现从此表单添加的数据?
function FormPage({ setData }) {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [id, setId] = useState(0);
const handleSubmit = (e) => {
e.preventDefault();
const book= { name, description, id}
fetch('link-from-api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(book)
}).then(() => {
console.log('new book added');
})
}
return (
<>
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
required
value={name}
onChange={(e) => setName(e.target.value)}
label="Name" />
<TextField
required
value={description}
onChange={(e) => setDescription(e.target.value)}
label="Description" />
<button type="submit" onClick={handleId}> set</button>
</form>
</>
);
}
export default FormPage;
当我添加一本新书时,我需要在这个文档中看到它:
function BooksPage() {
const [books, setBooks] = useState([]);
useEffect(() => {
fetch('link here')
.then(res => {
return res.json();
})
.then((data) => {
setBooks(data)
})
}, [])
return (
<Container>
<Header />
{books &&
<ListBooks props={books} />}
</Container>
)
}
谁能帮我?提前致谢。
解决方案
您需要使用lifting the state up
这里调用的概念。
books
在这两个组件的公共父组件中定义您的状态变量,FormPage
然后BooksPage
将此方法传递给组件 FormPage。
const addBook = (book) => {
setBooks(b => [...b, book])
}
调用此方法
const handleSubmit = (e) => {
e.preventDefault();
const book= { name, description, id}
fetch('link-from-api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(book)
}).then(() => {
console.log('new book added');
addBook(book)
})
}
books
并传递setBooks
到BooksPage 页面。
推荐阅读
- html - 使用管道输入数字 11 位小数不允许数字 > 999
- javascript - Azure DevOps Rest API getWorkItems 不返回指定的字段
- ios - 应用卡在核心数据初始化。怎么修?
- java - Java SQL INSERT INTO 使用 eclipse 函数不能与 Myconnection.getconnection() 一起使用;
- python - 如何修复 django 中的循环导入?
- youtube-data-api - YouTube API V3 发布之后/发布之前不工作
- batch-file - 运行批处理文件时在 > 或 >> 之前自动添加 1
- entity-framework - context.SaveChanges() 上的 .NET Core EF 主键错误
- api - 在 hmvc codeigniter 中使用用户授权时为 API 测试设置 Postman
- jakarta-ee - 修复 'java.lang.NoSuchMethodError: sun.security.ssl.SSLSessionImpl'