function Page({ data }) {
// Render data...
const itemList = data.items.map(item => {
return <Item key = {item.id} />
})
return(
<div>
{itemList}
</div>
)
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Page
我想在data.items
数组中推送一个新项目并更新UI。
通常useState()
可以实现,但是在这种情况下,数据是在服务器端获取的。
有没有简单的方法可以实现这一目标?
答案 0 :(得分:0)
import Axios from "axios";
const index = ({ data }) => {
return (
<div>
<ul>
{data.map(post => <li key={post.id}>
{post.title}
</li>)}
</ul>
</div>
)
}
export const getServerSideProps = async () => {
const res = await Axios(`https://jsonplaceholder.typicode.com/posts`);
const newPost = {
userId: 10,
id: 101,
title: 'at nam consequatur ea labore ea harum',
body: 'cupiditate quo est a modi nesciunt soluta\n' +
'ipsa voluptas error itaque dicta in\n' +
'autem qui minus magnam et distinctio eum\n' +
'accusamus ratione error aut'
}
const data = [...res.data, newPost];
return {
props: {
data
}
}
}
export default index;