分类 React 下的文章

  1. It is rendered once on the server - it is the root of your app
  2. App's getInitialProps is called before anything else - even before getInitialProps in _document.js
  3. It is created and mounted ONLY ONCE on the client - when the page first loads. Thereafter, on page navigation, App.getInitialProps is called before each page, and then its render function is called, to render the incoming page.

- 阅读剩余部分 -

最近沉迷 SSR,因为考虑到了一些需求:

  • SEO
  • Social sharing

当然了,谷歌牛逼,都能直接解析 SPA 了,但问题我主要还是一个用户体验上:用户点击一个 url,SPA 就 404 了,但一个体验很好的网站,显然希望是能够加载出来的。下面是Vuejs的SSR网站对SEO问题的解释:

Better SEO, as the search engine crawlers will directly see the fully rendered page.

Note that as of now, Google and Bing can index synchronous JavaScript applications just fine. Synchronous being the key word there. If your app starts with a loading spinner, then fetches content via Ajax, the crawler will not wait for you to finish. This means if you have content fetched asynchronously on pages where SEO is important, SSR might be necessary.

所以就开始了迁移,从 React SPA 迁移到 nextjs。

nextjs 很多大坑,比如说:

  • getInitialProps 只能在pages这个目录下用

    • _app.js 里不建议用 getInitialProps
  • 关于 router:

    • Link 其实是客户端 routing,
    • router ( useRouter 和 withRouter )的话, push就是服务端 routing,
    • router 不能像 react-router 那样带state (我看某个 issue 这么些的,想和各位确认一下)
  • PM2 部署

    • 还是需要用express做一个中间层
    • 也有用koa2做中间层的,但我没再折腾了
    • 如果不用,直接pm2 start next start也行,但我还是希望用到ecosystem.config.js这个文件写配置
  • Webpack配置的坑:

  • next.config.jsde 问题

    • 首先是不要用.env,而要用这个配置文件里的env
  • 一些迷

    • 反正就是总会出现一些迷一样的 error,反正还有点搞不清

首先,Next.js是个好学校,啊不,是个好框架;
其次,Next.js的文档也不算烂,但确实有点简陋,好多都是undocumented

Next.js有个feature叫做file-system routing:

By default, Next will serve each file in /pages under a pathname matching the filename (eg, /pages/some-file.js is served at site.com/some-file.

你可以设置一个option来turn it off:

// next.config.js
module.exports = {
  useFileSystemPublicRoutes: false,
}

我今天谈论的重点是这个问题:当我在Components/SomeComponenet.jsx里使用router(不论是useRouter还是withRouter),都会报错,错误信息这样的:

- 阅读剩余部分 -

React做的SPA,非常快,然而,对SEO很不友好,社交分享更是不行。
所以就必须考虑服务端渲染了,就是所谓的server side rendering。
最近在做这个迁移工作,很久了,都没搞定。一方面不太熟悉nextjs,一方面工作量也确实不小,代码复用性不是特别好,所以应该从一开始就考虑ssr,而不是做到一半再迁移过去。