Code Splitting + Server Side Rendering with react-router and Webpack
Code Splitting + Server Side Rendering with react-router and Webpack
- react + react-router + webpackでのコード分割の方法 → わかった
- 初期描画前にDBなど非同期操作を行い、その結果を見てデータを返したい場合のサーバ側実装 → わからない
- さらに、Server Side Renderingしたい場合 → わからない
2
Componentごとにデータfetchを管理するイメージか。たとえば、componentDidMount
のタイミングで各Componentから別途サーバAPIを叩くとか。つまり、initial rendering時には特に何も考えなくて良いのかもしれない。(SSRしない場合)
Load Initial Data via AJAX | React
SSRを考えないと、フローは下のようなイメージ。
クライアントから初期リクエスト ↓ サーバは不完全なHTML, JS, CSSを返却 ↓ クライアント側のComponent lifecycle開始 ↓ 各々のComponentが必要なデータをAPIサーバへfetch
2, 3
ComponentごとのfetchData()
を実行する感じ?
Server-Side Rendering with Redux and React-Router | Codementor
1に関して
My personal approach is to stick a static method
fetchData()
into every routing’s leaf node (if the routing is nested, I’d put it in the innermost one). By doing so, we can use react-router to match the URL to the component we’ll be rendering, and thus callingfetchData()
and obtaining the data entry point.
2に関して
fetchData()
をPromiseにしよう
注意
initial rendering時だけだが、サーバ側でfetchData()
によってデータフェッチを行っているにもかかわらず、その後Client側でも「ComponentDidMount()
」が問答無用で走るので、実質同じデータを2回取ってくることになる。これを防ぐには「ComponentDidMount()
」の中でdataが既に存在するかチェックするのが良いのでは。と記事の著者はいっている。
調べていて湧いた疑問
reactjsでは通信のタイミングは主に「URLが変わった時」「ComponentDidMount()
」 の2種類。自分が今まで書いたものだと、前者のタイミングでしか通信を行っていなかった。FLUXをちゃんと読み直したい。
→ fluxで見ると、XHRはAction (ActionCreators)で行っている。(URL云々は話に出ない)
reactjs - In Flux architecture, how do you manage client side routing / url states? - Stack Overflowにあるように、Flux界隈ではURL Routingのことは議題から除外しているっぽい。
Michelle Tilleyの答え
The strategy is that the URL/routes should determine which components get mounted, and the components request data from the stores based on the route parameters and other application state as necessary.
これは、俺の思想と同じ。 ユーザアクションによって、アプリのステートが変化するならば、それを必ずURL更新に還元してあげる。URL更新のハンドラで通信を行うイメージ。
webpack 2.0 以降なら System.import
が使える
Code Splitting for React Router with ES6 Imports - Modus Create
ディレクトリ構成
Implicit Code Splitting and Chunk Loading with React Router and Webpack | Henley Edition