const Index = () => (
<div>
<p>Hello Next.js</p>
</div>
)
export default Index
5.新增其他route時只要在pages內加入檔案即可。
/pages/about.js
export default () => (
<div>
<p>This is the about page</p>
</div>
)
2.新增client Route
我們把index.js改為如下
import Link from 'next/link'
const Index = () => (
<div>
<Link href="/about">
<a>About Page</a>
</Link>
<p>Hello Next.js</p>
</div>
)
export default Index
3.新增共用layout component
4.引入<script>或是其他html tag
import Layout from '../components/MyLayout.js'
import Head from 'next/head'
export default () => (
<Layout>
<Head>
<script src="https://checkout.stripe.com/v2/checkout.js"></script>
</Head>
<p>This is the about page</p>
</Layout>
)
5.讀取url
加入withRouter
之後即可讀取到router的props
import {withRouter} from 'next/router'
import Layout from '../components/MyLayout.js'
const Content = withRouter((props) => (
<div>
<h1>{props.router.query.title}</h1>
<p>This is the blog post content.</p>
</div>
))
const Page = (props) => (
<Layout>
<Content />
</Layout>
)
export default Page
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
const Index = (props) => (
<Layout>
<h1>Batman TV Shows</h1>
<ul>
{props.shows.map(({show}) => (
<li key={show.id}>
<Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}>
<a>{show.name}</a>
</Link>
</li>
))}
</ul>
</Layout>
)
Index.getInitialProps = async function() {
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
const data = await res.json()
console.log(`Show data fetched. Count: ${data.length}`)
return {
shows: data
}
}
export default Index
更新版:
Next.js 9.3
export async function getStaticProps() {
// Call an external API endpoint to get posts
const res = await fetch(`${process.env.NEXT_PUBLIC_API_ENDPOINT}/}`)
const data = await res.json()
return {
props: {
data,
},
}
}
export default function Home({ data }) {
...
}
他跟create-react-app 不同之處在於他是server side render,所以沒有直接build然後用serve static的方式,而是需要啟動next的server然後用nginx做reverse proxy的方式。
location / {
# default port, could be changed if you use next with custom server
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
# if you have try_files like this, remove it from our block
# otherwise next app will not work properly
# try_files $uri $uri/ =404;
}