Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

React 服务端渲染框架 next.js

$
0
0

next.js服务端渲染框架真的是一个救命的稻草。在此之前我一直在寻找 React服务端渲染的框架,一直没有一个满意的答案,直到碰到 next.js

那么 next.js与标准的 React.Component有何区别吗?

通过阅读代码我发现 next.js多了一个初始化 props的函数。

// 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被标记为异步的函数 (await), 因此返回一个 Promise或者 async标记的函数。这也为加载异步数据提供了保障。

Component.getInitialProps的参数 ctx,浏览器端和服务器端不相同,依然通过代码来发现。

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

从两段代码可以得知服务端多了 { req, res }req是服务端 Request对象, res是服务端 Response。有了这两东西就可以做很多事情了。

当然 next.js作为一个框架,做的事情不止这一些,还有一些和神奇的东西,需要使用时进一步了解。

原文详见: http://www.jianshu.com/p/84515a6d75a4


Viewing all articles
Browse latest Browse all 14821

Trending Articles