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)一步了解。