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;
}

 

转载于:https://www.cnblogs.com/escapist/p/11371319.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值