React 服務(wù)端渲染框架 next.js

next.js 服務(wù)端渲染框架真的是一個救命的稻草。在此之前我一直在尋找 React 服務(wù)端渲染的框架,一直沒有一個滿意的答案,直到碰到 next.js。

那么 next.js 與標(biāo)準(zhǔn)的 React.Component 有何區(qū)別嗎?

通過閱讀代碼我發(fā)現(xiàn) next.js 多了一個初始化 props 的函數(shù)。

// file: lib/utils.js
export async function loadGetInitialProps (Component, ctx) {
  if (!Component.getInitialProps) return {}

  const props = await Component.getInitialProps(ctx)
  if (!props && (!ctx.res || !ctx.res.finished)) {
    const compName = Component.displayName || Component.name
    const message = `"${compName}.getInitialProps()" should resolve to an object. But found "${props}" instead.`
    throw new Error(message)
  }
  return props
}

next.js 使用 Component.getInitialProps 來初始化組件。
Component.getInitialProps 被標(biāo)記為異步的函數(shù) (await), 因此返回一個 Promise 或者 async 標(biāo)記的函數(shù)。這也為加載異步數(shù)據(jù)提供了保障。

Component.getInitialProps 的參數(shù) ctx,瀏覽器端和服務(wù)器端不相同,依然通過代碼來發(fā)現(xiàn)。

// file: server/render.js#L52
const ctx = { err, req, res, pathname, query }
// file: client/index.js#L102
props = await loadGetInitialProps(Component, { err, pathname, query })

從兩段代碼可以得知服務(wù)端多了 { req, res }req 是服務(wù)端 Request 對象, res 是服務(wù)端 Response。有了這兩東西就可以做很多事情了。

當(dāng)然 next.js 作為一個框架,做的事情不止這一些,還有一些和神奇的東西,需要使用時進(jìn)一步了解。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容