我正在渲染来自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
的概念。
在FormPage
和BooksPage
这两个组件的共同父组件中定义状态变量books
将此方法传递给组件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
传递给页面bookpage。
您可以将获取移动到一个单独的函数,并在POST完成后再次调用
function BooksPage() {
const [books, setBooks] = useState([]);
function fetchBooks() {
fetch('link here')
.then(res => {
return res.json();
})
.then((data) => {
setBooks(data)
})
}
useEffect(() => {
fetchBooks();
}, [])
return (
<Container>
<Header />
{books &&
<ListBooks props={books} />}
<FormPage fetchBooks={fetchBooks} />
</Container>
)
}
和在你的形式:
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');
// fetch again
fetchBooks();
})
}