开始
起步
安装
npm install --save next react react-dom
Next.js 只支持 React 16
由于某些原因我们不得不放弃支持 React 15
添加下面的配置到package.json 的script字段中
{ "script": { "dev": "next", "build": "next build" "start": "next start" } }
之后,文件系统就是主要的API。每一个.js文件都成为一条被自动处理和呈现的路径
在项目中创建 ./pages/index.js
export default () => <div>Welcome to next.js!</div>
运行 npm run dev
跳转 http://localhost:3000
,如果想要使用其他端口,你可以使用 npm run dev -- -p <your port here>
目前为止我们做到:
代码的自动的转换与打包(使用webpack和babel)
代码热更新
服务器端渲染
./pages
静态文件服务
./static/
映射到/static/
很简单吧!看看这个案列 sample app - nextgram
代码的自动拆分
您声明的每个import
都会捆绑并与每个页面一起提供。 这意味着页面从不加载不必要的代码
import cowsay from 'cowsay-browser'export default () => <pre> {cowsay.say({ text: 'hi there!' })} </pre>
CSS
内联css支持
案例
我们支持 styled-jsx 书写CSS, The aim is to support "shadow CSS" similar to Web Components, which unfortunately do not support server-rendering and are JS-only.
export default () => <div> Hello world <p>scoped!</p> <style jsx>{` p { color: blue; } div { background: red; } @media (max-width: 600px) { div { background: blue; } } `}</style> <style global jsx>{` body { background: black; } `}</style> </div>
更多案例请查看 styled-jsx 文档
css-in-js
案列
可以使用现有的 CSS-in-JS 方案,最简单的方式是使用内联
export default () => <p style={{ color:'red' }}>hi</p>
要使用更复杂的CSS-in-JS解决方案,您通常必须为服务器端呈现实现样式刷新。我们通过允许您定义自己的包装每个页面的自定义<Document>组件来实现这一点。(To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own custom <Document> component that wraps each page.)
引入 CSS / Sass / Less / Stylus files
要支持导入.css、.scss、.less或.styl文件,您可以使用这些模块,它们为服务器呈现的应用程序配置合理的默认值
静态文件服务(比如图片)
在你的项目根目录创建一个static
文件,在你的代码里可以引入这些静态文件
export default ()=> <img src="/static/my-image.png" alt='my image' />
head
案列
我们公开了一个内置组件,用于向<head>
内追加元素, 类似于react-helmet
import Head from 'next/head'export default () => <div> <Head> <title>My page title</title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> </Head> <p>Hello world!</p> </div>
为了避免重复标签在你的<head>
,你可以使用key属性,这将确保标签只呈现一次:
import Head from 'next/head' export default () => ( <div> <Head> <title>My page title</title> <meta name="viewport" content="initial-scale=1.0, width=device-width" key="viewport" /> </Head> <Head> <meta name="viewport" content="initial-scale=1.2, width=device-width" key="viewport" /> </Head> <p>Hello world!</p> </div>)
上面的案列只有第二个会被渲染
在组件被卸载时,
<head>
内的内容也会卸载,请不要假设组件更换追加head
请求数据与组件的生命周期
案列
当您需要状态、生命周期钩子或初始数据填充时,您可以导出一个 React.Component
(而不是无状态函数,如上面所示)
(When you need state, lifecycle hooks or initial data population you can export a React.Component (instead of a stateless function, like shown above):)
import React from 'react'export default class extends React.Component { static async getInitialProps({ req }) { const userAgent = req ? req.headers['user-agent'] : navigator.userAgent return { userAgent } } render() { return ( <div> Hello World {this.props.userAgent} </div> ) } }
在页面加载时加载数据,我们使用 getInititialProps
, 它是一个异步
的静态方法,它可以异步地获取任何解析为JavaScript普通对象的内容,去填充部分props
从getInitialProps返回的数据在服务器呈现时被序列化,类似于JSON.stringify。确保getInitialProps返回的对象是一个普通对象,而不使用Date、Map或者set
初始加载的页面,getInititialProps
是仅在服务器上执行的,getInitialProps
只有在切换路由或者使用Link
和路由api
时才会在客户端执行
getInitialProps
不可以使用在 children components 只可以使用在 Page 中
如果在
getInitialProps
中使用一些服务器模块,请确保正确地使用它们。否则,它导致你的app变慢
您还可以为无状态组件定义getInitialProps
生命周期方法:
const Page = ({stars}) => <div> Next stars :{stars} </div> Page.getInitialProps = async({req}) => { const res = await fetch('https://api.github.com/repos/zeit/next.js') const json = await res.json() return { stars: json.stargazers_count } } export default Page
getInitialProps
接收一个 context object 有如下属性:
pathname - path section of URL
query - query string section of URL parsed as an object
asPath - String of the actual path (including the query) shows in the browser
req - HTTP request object (server only)
res - HTTP response object (server only)
jsonPageRes - Fetch Response object (client only)
err - Error object if any error is encountered during the rendering
路由
With<Link>
案列
在两个页面之间,客户端可以使用Link
实现页面之间的切换
// pages/index.jsimport Link from 'next/link'export default () => <div> Click{' '} <Link href="/about"> <a>here</a> </Link>{' '} to read more </div>
// pages/about.jsexport default () => <p>Welcome to About!</p>
使用
<Link prefetch>
可以达到最大的性能,同时在后台跳转和数据预取 prefetch&Link
客户端路由的行为与浏览器完全相同
获取组件
如果定义了
getInitialProps
,则获取数据。 如果发生错误,则呈现_error.js
在第1步和第2步完成后,
pushState
才会执行,然后组件渲染
每个顶级组件都使用以下API接收url属性:
pathname
- String of the current path excluding the query stringquery
- Object with the parsed query string. Defaults to {}asPath
- String of the actual path (including the query) shows in the browserpush(url, as=url)
- performs a pushState call with the given urlreplace(url, as=url)
- performs a replaceState call with the given url
第二个作为push
和replace
的参数是URL的可选装饰。 在服务器上配置自定义路由时很有用。
With URL Object
作者:will___
链接:https://www.jianshu.com/p/258fba795ca2
x