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