nextjs做为koa中间件的使用

react客户端渲染的缺点:首屏速度慢,对SEO不友好css

 

浏览器请求步骤                                                        客户端跳转html

1. 浏览器发起请求 /index                                           1.  点击按钮node

2. koa接受请求,而且调用nextjs                                 2. 异步加载组件的jsreact

3. nextjs开始渲染                                                     3. 调用页面的getInitialPropsredis

4. 调用app的getInitialProps                                       4. 数据返回,页面跳转数据库

5. 调用页面的 getInitialProps                                     5. 渲染新页面npm

6. 渲染出最终的 htmljson

7. 返回给浏览器浏览器

 

^ 表示升级小版本,不会升级大的版本服务器

大版本通常只有大改动,才会更新

小版本通常是修复bug, 次版本是一些细微修改

 

建立next项目的方式

一. 手动建立

npm init     yarn add  react react-dom  next

"dev": "next"    "start": "next start"   启动正式的服务   "build": "next build"

 

二. 使用 create-next-app

npm i -g create-next-app  

npx  create-next-app   app-project

yarn create   app-project

create-next-app   app-project

 

在pages里面没有引入 React, 是由于在全局中已经引入了

React.createElement('div', {} , 'hello')

 

nextjs 自身带有服务器,可是只处理 ssr渲染

处理HTTP请求,而且根据请求返回响应的内容

没法处理服务器  数据接口   数据库链接  session状态

 

koa是一个很是流行的轻量nodejs服务端框架,自己不封装什么功能

很是易于扩展,变成范式很是符合js特性

 

next做为koa的一个中间价        

const Koa = require('koa')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'  // 名字必须是这一个名字
const app = next({ dev})
const handler = app.getRequestHandler() //

app.prepare().then(()=>{ // 等待页面编译完成
  const server = new Koa()
  server.use(async (ctx,next)=>{
    await handler(ctx.req,ctx.res) // 等待nextjs执行完成
    ctx.respond = false
  })
  server.listen(3000,()=>{
    console.log('listen on 3000')
  })
})

 

返回 render2 

 

koa-router是 koa的一个中间件

server.use(router,routes())

ctx.param.id

 

ctx.res    ctx.req 原生的

ctx.response      ctx.request  封装后的Koa对象

ctx.body = { success: true }    ctx.set('content-type', 'application/json')

 

requirepass  密码           配置文件配置项

redis-cli   -p 6379

> auth  12345      就能够正确操做了

> setenx   c   10  1     设置过时时间      del  c 删除

ioredis 链接Redis

 

nextjs默认不支持 css文件引入    为何?      建议 css in js

 

yarn add @zeit/next-css

next.config.js 配置文件

如何分模块加载组件     不包括css文件

 

_app.js

 

const withCss = require("@zeit/next-css")

if (require !== 'undefined'){
  require.extensions['.css'] = file=>{}
}

module.exports = withCss({})

hoc的使用

export default (Comp) => {
   function hoc({Component, pageProps, ...test}){
    if(pageProps){ // 并非每一个页面都有 pageProps
      pageProps.teid=123456;
    }
    return <Comp Component={Component} pageProps={pageProps} {...test} />
  }
  hoc.getInitialProps = Comp.getInitialProps; // 这一个很是关键
  return hoc;
}
相关文章
相关标签/搜索