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;
}
相關文章
相關標籤/搜索