Nextjs简介

Nextjs

next.js是一个非常棒的轻量级的react同构框架,使用它可以快速的开发出基于服务端渲染的react应用。

Nextjs官网:https://nextjs.org/

Nextjs官方demo:https://github.com/zeit/next.js/tree/canary/examples

Nextjs中文文档:https://nextjs.frontendx.cn/

路由处理

官方文档:https://nextjs.org/docs#routing

页面中直接跳转用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Link from 'next/link'

function Home() {
return (
<>
<ul>
<li>Home</li>
<li>
<Link href="/about">
<a>About Us</a>
</Link>
</li>
</ul>

<h1>This is our homepage.</h1>
</>
)
}

export default Home

js方法中跳转:

1
2
3
4
5
6
7
8
9
10
11
import Router from 'next/router'

function ReadMore() {
return (
<div>
Click <span onClick={() => Router.push('/about')}>here</span> to read more
</div>
)
}

export default ReadMore

Dynamic Import

官方文档:https://nextjs.org/docs#dynamic-import

因为Nextjs代码跑起来会走两套环境,分别是客户端和服务端环境,客户端环境和常规react开发一样,服务端环境就比较麻烦,windowlocalStoragenavigator.userAgent这些就会在服务端报undefined错误。所以需要控制好代码有哪些是在两个环境通用,哪些只能在客户端环境运行。

比较常见的就是视频播放,视频播放器即不需要也没办法在服务端渲染,那么如何控制它只在客户端渲染?Nextjs提供了Dynamic Import方法来处理该问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)

function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
)
}

export default Home

自定义配置

官方文档:https://nextjs.org/docs#custom-configuration