学习文档

开始

起步

安装

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 () => 
Welcome to next.js!

运行 npm run dev 跳转 http://localhost:3000 ,如果想要使用其他端口,你可以使用 npm run dev -- -p

目前为止我们做到:

  • 代码的自动的转换与打包(使用webpack和babel)
  • 代码热更新
  • 服务器端渲染 ./pages
  • 静态文件服务 ./static/ 映射到 /static/

很简单吧!看看这个案列 sample app - nextgram

代码的自动拆分

您声明的每个import都会捆绑并与每个页面一起提供。 这意味着页面从不加载不必要的代码

import cowsay from 'cowsay-browser'

export default () =>
  
    {cowsay.say({ text: 'hi there!' })}
  

CSS

内联css支持

案例

  • Basic 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 () =>
  
Hello world

scoped!

更多案例请查看 styled-jsx 文档

css-in-js

案列

  • Styled components
  • Styletron
  • Glamor
  • Glamorous
  • Cxs
  • Aphrodite
  • Fela

可以使用现有的 CSS-in-JS 方案,最简单的方式是使用内联

export default () => 

hi

要使用更复杂的CSS-in-JS解决方案,您通常必须为服务器端呈现实现样式刷新。我们通过允许您定义自己的包装每个页面的自定义组件来实现这一点。(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 component that wraps each page.)

引入 CSS / Sass / Less / Stylus files

要支持导入.css、.scss、.less或.styl文件,您可以使用这些模块,它们为服务器呈现的应用程序配置合理的默认值

  • @zeit/next-css
  • @zeit/next-sass
  • @zeit/next-less
  • @zeit/next-stylus

静态文件服务(比如图片)

在你的项目根目录创建一个static文件,在你的代码里可以引入这些静态文件

export default ()=> my image

head

案列

  • Head elements
  • Layout component

我们公开了一个内置组件,用于向内追加元素, 类似于react-helmet

import Head from 'next/head'
export default () => 
  
My page title

Hello world!

为了避免重复标签在你的,你可以使用key属性,这将确保标签只呈现一次:

import Head from 'next/head'
export default () => (
  
My page title

Hello world!

)

上面的案列只有第二个会被渲染

在组件被卸载时,内的内容也会卸载,请不要假设组件更换追加head

请求数据与组件的生命周期

案列

  • Data fetch

当您需要状态、生命周期钩子或初始数据填充时,您可以导出一个 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 (
      
Hello World {this.props.userAgent}
) } }

在页面加载时加载数据,我们使用 getInititialProps, 它是一个异步的静态方法,它可以异步地获取任何解析为JavaScript普通对象的内容,去填充部分props

从getInitialProps返回的数据在服务器呈现时被序列化,类似于JSON.stringify。确保getInitialProps返回的对象是一个普通对象,而不使用Date、Map或者set

初始加载的页面,getInititialProps是仅在服务器上执行的,getInitialProps只有在切换路由或者使用Link路由api时才会在客户端执行

getInitialProps不可以使用在 children components 只可以使用在 Page

如果在getInitialProps中使用一些服务器模块,请确保正确地使用它们。否则,它导致你的app变慢

您还可以为无状态组件定义getInitialProps生命周期方法:

const Page = ({stars}) =>
  
Next stars :{stars}
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.js
import Link from 'next/link'

export default () =>
  
Click{' '} here {' '} to read more
// pages/about.js
export default () => 

Welcome to About!

使用可以达到最大的性能,同时在后台跳转和数据预取 prefetch&Link

客户端路由的行为与浏览器完全相同

  1. 获取组件
  2. 如果定义了getInitialProps,则获取数据。 如果发生错误,则呈现_error.js
  3. 在第1步和第2步完成后,pushState才会执行,然后组件渲染

每个顶级组件都使用以下API接收url属性:

  • pathname - String of the current path excluding the query string
  • query - Object with the parsed query string. Defaults to {}
  • asPath - String of the actual path (including the query) shows in the browser
  • push(url, as=url) - performs a pushState call with the given url
  • replace(url, as=url) - performs a replaceState call with the given url

第二个作为pushreplace的参数是URL的可选装饰。 在服务器上配置自定义路由时很有用。

With URL Object

案例

  • With URL Object Routing

你可能感兴趣的:(学习文档)