React使用next.js实现服务器端渲染

什么是服务端渲染及优势

  1. 服务端渲染(Server side rendering),是指通过服务器执行React页面的渲染和生成,并返回给客户端静态的HTML页面。
  2. 服务端渲染主要优势:
    • SEO
    • 首屏渲染友好
    • 速度相对快

使用React编写出来的程序是单页的应用程序,前端请求会都是一个html模板,对于信息分发类或者公众网站来说致命,SEO无法优化,搜索引擎无法找到网站想要分发出去的东西。使用服务端渲染每一个路径都会返回不同的html,包含不同的head,可以对其进行SEO优化。实际上React更适合制作后台系统,软件服务,无需被搜索引擎抓取,如果非必要,也可以选择使用传统的开发方法。

Next

找到一个还算不错我中文文档(非官方)
https://yq.aliyun.com/articles/610315

安装方法参考文档

  • getInitialProps

    • Next改变了组件的getInitialProps方法,传入了一个上下文对象,这个对象在服务端和客户端时候有不同的属性。因此可以在组件中处理上下文对象。getInitialProps 接收的上下文对象包含以下属性:
      • pathname - URL的 path部分
      • query - URL的 query string部分,并且其已经被解析成了一个对象
      • asPath - 在浏览器上展示的实际路径(包括 query字符串)
      • req - HTTP request 对象 (只存在于服务器端)
      • res - HTTP response 对象 (只存在于服务器端)
      • jsonPageRes - 获取的响应数据对象 Fetch Response (只存在于客户端)
      • err - 渲染时发生错误抛出的错误对象
  • 使用sass

    npm install @zeit/next-sass node-sass -s

  • static静态目录
    使用Next.js提供static静态路径,只需要在项目中创建一个static路径,即可通过/static/*.jpg进行访问:
    <img src='/static/tset.jpg' />
  • 缓存
    npm install lru-cache –save
    编辑server.js,添加如下代码:
const LRUCache = require('lru-cache')

// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
  max: 100,
  maxAge: 1000 * 60 * 60 // 1hour
})

// Use the `renderAndCache` utility defined below to serve pages
server.get('/', (req, res) => {
renderAndCache(req, res, '/')
})

/*
 * NB: make sure to modify this to take into account anything that should trigger
 * an immediate page change (e.g a locale stored in req.session)
 */
function getCacheKey (req) {
  return `${req.url}`
}

function renderAndCache (req, res, pagePath, queryParams) {
  const key = getCacheKey(req)

  // If we have a page in the cache, let's serve it
  if (ssrCache.has(key)) {
    console.log(`CACHE HIT: ${key}`)
    res.send(ssrCache.get(key))
    return
  }

  // If not let's render the page into HTML
  app.renderToHTML(req, res, pagePath, queryParams)
    .then((html) => {
      // Let's cache this page
      console.log(`CACHE MISS: ${key}`)
      ssrCache.set(key, html)

      res.send(html)
    })
    .catch((err) => {
      app.renderError(err, req, res, pagePath, queryParams)
    })
}

缓存使用的问题:当产生错误页面也会缓存上,并且每次读取均为错误页面,即使编译没有问题也会读取出错误页面。解决:更改server.js,使请求成功的时候才存入缓存,即使页面出错也不会出现之前的问题。代码:修改renderAndCache方法

function renderAndCache (req, res, pagePath, queryParams) {
      const key = getCacheKey(req)
      // 如果在缓存中存在页面,则直接从缓存中读取,目前不完善,不能判断出错
      if (ssrCache.has(key)) {
              console.log(`CACHE HIT: ${key}`)
              res.send(ssrCache.get(key))
              return    
      }

      // 如果缓存中没有页面,则直接返回页面,并将页面添加到缓存中
      app.renderToHTML(req, res, pagePath, queryParams)
        .then((html) => {
          // Let's cache this page
          console.log(`CACHE MISS: ${key}`)
          //将请求成功的页面添加进缓存
          if(res.statusCode === 200){
            ssrCache.set(key, html)
          }else{
            ssrCache.del(key);
          }

          // console.log(res.statusCode);
          res.send(html)
        })
        .catch((err) => {
          app.renderError(err, req, res, pagePath, queryParams)
        })
    }

next全部例子(整合epress等)

demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值