未验证 提交 fe4da734 编写于 作者: J Josiah Wiebe 提交者: GitHub

feat: update api-routes example to SSG (#11019)

* feat: update api-routes example to SSG

* Update examples/api-routes/components/Person.js
Co-authored-by: NLuis Alvarez D <luis@zeit.co>
上级 0f0013b9
......@@ -2,7 +2,7 @@ import Link from 'next/link'
export default ({ person }) => (
<li>
<Link href={`/person?id=${person.id}`}>
<Link href="/person/[id]" as={`/person/${person.id}`}>
<a>{person.name}</a>
</Link>
</li>
......
......@@ -7,8 +7,8 @@
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "latest",
"node-fetch": "2.6.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
......
import Person from '../components/Person'
import fetch from 'isomorphic-unfetch'
import fetch from 'node-fetch'
const Index = ({ people }) => (
<ul>
......@@ -9,11 +9,11 @@ const Index = ({ people }) => (
</ul>
)
Index.getInitialProps = async () => {
export async function getStaticProps() {
const response = await fetch('http://localhost:3000/api/people')
const people = await response.json()
return { people }
return { props: { people } }
}
export default Index
import fetch from 'isomorphic-unfetch'
import fetch from 'node-fetch'
const Person = ({ data, status }) =>
status === 200 ? (
......@@ -30,11 +30,29 @@ const Person = ({ data, status }) =>
<p>{data.message}</p>
)
Person.getInitialProps = async ({ query }) => {
const response = await fetch(`http://localhost:3000/api/people/${query.id}`)
export async function getStaticPaths() {
const response = await fetch('http://localhost:3000/api/people')
const data = await response.json()
const paths = data.map(person => ({
params: {
id: person.id,
},
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const response = await fetch(`http://localhost:3000/api/people/${params.id}`)
const data = await response.json()
return { data, status: response.status }
return {
props: {
data,
status: response.status,
},
}
}
export default Person
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册