原始文档在 https://github.com/developerw… 如今搬过来.
进修 Next.js: 入门
进修 Next.js: 页面之间的导航
进修 Next.js: 运用同享组件
进修 Next.js: 建立动态内容
进修 Next.js: 运用路由掩码建立清洁的URL
进修 Next.js: 清洁URL的服务器支撑
进修 Next.js: 猎取数据
进修 Next.js: 布置
建立动态页面
如今,我们知道了怎样运用多个页面建立一个基本的Next.js运用顺序. 为了建立页面, 我们须要在磁盘上建立现实的文件.
然则, 在实在的运用场景下,我们一般须要经由过程数据建立动态的页面, 用动态的体式格局显现页面内容. 在Next.js中有多种体式格局来完成这个目标.
起首, 我们运用查询串来建立一个动态的页面. 我们建立一个简朴的博客运用顺序. 在Index页面显现一个博客列表.
当你点击博客题目时, 能够看到博客的具体内容.
如今, 让我们最先建立这个博客顺序.
设置
为了根据本课程进修, 须要有一个示例Next.js运用顺序, 为此, 你能够下载下面的这个运用顺序作为进修案例:
git clone https://github.com/arunoda/learnnextjs-demo.git
cd learnnextjs-demo
git checkout using-shared-components
能够用下面的敕令来运转:
npm install
npm run dev
如今, 接见 http://localhost:3000/.
增加博客列表
起首, 让我们在首页增加博客题目列表, 增加下面的代码到 pages/index.js
模块文件中.
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
const PostLink = (props) => (
<li>
<Link href={`/post?title=${props.title}`}>
<a>{props.title}</a>
</Link>
</li>
)
export default () => (
<Layout>
<h1>My Blog</h1>
<ul>
<PostLink title="Hello Next.js"/>
<PostLink title="Learn Next.js is awesome"/>
<PostLink title="Deploy apps with Zeit"/>
</ul>
</Layout>
)
然后, 方位 http://localhost:3000, 你会看到下面的内容:
经由过程查询串通报数据
我们经由过程查询串参数通报数据, 在这个例子中为”title”查询串论述, 示意博客的题目, 我们下面为博客的题目完成一个自定义的PostLink
组件.
const PostLink = (props) => (
<li>
<Link href={`/post?title=${props.title}`}>
<a>{props.title}</a>
</Link>
</li>
)
建立博客页面
建立博客页面, 显现博客内容, 为此我们须要从查询串中猎取题目. 下面建立一个 pages/post.js
文件, 并增加以下内容:
import Layout from '../components/MyLayout.js'
export default (props) => (
<Layout>
<h1>{props.url.query.title}</h1>
<p>This is the blog post content.</p>
</Layout>
)
如今, 页面看起来像如许:
每一个页面取得一个”URL”属性, 个中包括当前URL相干的详细信息
这里我们运用”query”对象, 它包括查询串参数
然后, 我们从
props.url.query.title
猎取博客的题目
如今, 我们做一点纤细的修正, 替代 pages/post.js
的内容为以下:
import Layout from '../components/MyLayout.js'
const Content = (props) => (
<div>
<h1>{props.url.query.title}</h1>
<p>This is the blog post content.</p>
</div>
)
export default () => (
<Layout>
<Content />
</Layout>
)
然后接见 http://localhost:3000/post?title=Hello%20Next.js 看是什么结果?
特别属性”url”
你看到了, 代码会抛出一个以下所示的毛病页面:
这是由于, url
属性仅暴露给了页面的根主键. 并未暴露给页面中的其他组件. 但假如须要, 能够像下面如许把url
属性通报给其他组件.
export default (props) => (
<Layout>
<Content url={props.url} />
</Layout>
)
末了
如今我们已进修到了怎样运用查询串建立动态页面. 但这仅仅只是最先. 一个动态页面须要更多的信息来衬着, 我们不太可能经由过程查询串通报一切的信息. 我们想要有一个清洁的像如许的URL: http://localhost:3000/blog/hello-nextjs.
接下来, 我们将会学到关于这方面的一切信息. 这是一切其他事变的基本.