nextjs作为koa中间件的使用

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

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

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

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

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

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

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

6. 渲染出最终的 html

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 env = process.env.NODE_ENV !== 'production'
const app = next({ env })
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;
}

猜你喜欢

转载自www.cnblogs.com/escapist/p/11371319.html