Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Redux and React Server Rendering
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
hui.liu
April 10, 2016
Technology
120
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Redux and React Server Rendering
hui.liu
April 10, 2016
More Decks by hui.liu
See All by hui.liu
How to build an online IDE with React
hulufei
0
540
利用Grunt打造前端工作流
hulufei
5
1.2k
Other Decks in Technology
See All in Technology
“全部コピーしない”ファイルデータの活用 : — FSx for ONTAP × S3 Tables × Icebergで作るメタデータカタログ
yoshiki0705
0
130
AIで政治は変わるのか? — 中高生と考えたAI時代の民主主義(東海高校サタデープログラム)
eitarosuda
0
310
次世代ランサムウェア対策の考察 / 20260704 Mitsutoshi Matsuo
shift_evolve
PRO
5
1.5k
CVE-2026-20833_脆弱性対応とAES 化について
jukishiya
0
300
AWS Summit Japan 2026の振り返りと2027へ向けて / AWS Summit Japan 2026 Recap and Prospects for 2027
kaminashi
1
150
スタートアップにおけるアジャイルの実践について #shibuyagile
murabayashi
2
840
AIエージェントとPhysical AIが拓く製造業の変革(ハノーバーメッセリキャップ)
iotcomjpadmin
0
190
初めてのDatabricks勉強会
taka_aki
2
220
「ビジネスがわかるエンジニア」とは何か?
ryooob
0
440
Docker Desktop不要の時代が来る? WSL標準の「wslc」で Linuxコンテナを動かしてみた.
ueponx
0
370
Text-to-SQLをAgentCoreで実現し、生成されるSQLの精度を定量的に評価する
yakumo
2
260
AWS Summit の片隅で、体育座りしながらコミュニティがにぎわう理由を考えた
k_adachi_01
2
330
Featured
See All Featured
Large-scale JavaScript Application Architecture
addyosmani
515
110k
Rebuilding a faster, lazier Slack
samanthasiow
85
9.5k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
2k
Claude Code のすすめ
schroneko
67
230k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
250
1.3M
Joys of Absence: A Defence of Solitary Play
codingconduct
1
400
Noah Learner - AI + Me: how we built a GSC Bulk Export data pipeline
techseoconnect
PRO
0
210
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.2k
From π to Pie charts
rasagy
0
220
Making the Leap to Tech Lead
cromwellryan
135
9.9k
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2k
Done Done
chrislema
186
16k
Transcript
Redux Ө React ๐ۓ ᒒວ
ڝᬄ (@hulufei)
Why Server Rendering • Single Page Application (SPA) • Search
Engine Indexability (SEO)
Universal JavaScript Server Browser SPA Rendering
–Nick Dreckshage “react made it extremely easy.”
React Virtual DOM Server Browser SPA <App /> <div>…</div> renderToString()
UI Җ f(state)
None
– reactjs/redux “Redux is a predictable state container for JavaScript
apps.”
Redux Basic • Action • Reducer • Store
// Default function actionCreator() { return { type: 'ACTION_TYPE_CONSTANT', payload:
'payload' } } Action { type: ‘TYPE_CONSTANT’, payload: payload } thunk middleware promise middleware // Thunk function actionCreator() { return (dispatch) => { dispatch({ type: 'ACTION_TYPE_CONSTANT', payload: 'xx' }) // Async operation } } // Promise function actionCreator() { return { type: 'ACTION_TYPE_CONSTANT', payload: Promise.resolve(‘payload') } }
Reducer function reducer(state, action) { switch(action.type) { case 'ACTION_TYPE_CONSTANT': //
Update state return newState; default: return state; } } (previousState, action) => newState
Store import { createStore } from 'redux' import rootReducer from
'./reducers' let store = createStore(rootReducer) ӞӻଫአํӬՐํӞӻ Store // store.getState() ᬬࢧ State ᇫா // store.dispatch(action) ݎ reducer ๅෛ State // store.subscribe(listener) ፊލ State ๅෛ
Data Flow • action ฎӞӻ۱ތ { type, payload } ጱ
• reducer ڍහ᭗ᬦ store.dispatch(action) ݎ • reducer ڍහളݑ (state, action) ӷӻ݇හ • reducer ڍහڣෙ action.type ᆐݸ॒ቘଫጱ action.payload හഝๅ ෛᇫா҅ᬬࢧӞӻෛጱ state • store.subscribe(listener) ፊލ state ๅෛ
react-redux // index.js import { render } from 'react-dom'; import
{ Provider } from 'react-redux'; import App from './app'; render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); // app.js class App extends Component { ... } export default connect( mapStateToProps, mapDispatchProps )(App); <Provider /> connect const mapStateToProps = (state) => ({ propA: stateA, … }) const mapDispatchProps = (dispatch) => ({ propDoAction: (args) => dispatch(actionCreator(args)) ... })
Server Rendering Server Browser SPA UI = f(state) initialState Rendering
Server Rendering import { renderToString } from 'react-dom/server'; function renderFullPage(html,
initialState) { return ` <!DOCTYPE html> ... <div id=“root”>${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; </script> ... ` } app.use((req, res) => { store.dispatch(fetchActionCreator()) .then(_ => { const html = renderToString( <Provider store={store}> <App /> </Provider> ); res.end(renderFullPage(html, store.getState())); }); }); }); Browser SPA const initialState = window.__INITIAL_STATE__; const store = createStore(rootReducer, initialState); Browser SPA componentDidMount() { store.dispatch(fetchActionCreator()); }
None
react-router (Client) import { Route, IndexRoute } from 'react-router'; const
Container = (props) => <div>{props.children}</div>; const routes = ( <Route path="/" component={Container} > <IndexRoute component={App} /> <Route path=“path/:other” component={Other} /> </Route> ); export default routes;
react-router (Server) import { renderToString } from 'react-dom/server' import {
match, RouterContext } from 'react-router' import routes from './routes' function renderFullPage(html, initialState) { … } app.use((req, res) => { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message) } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if (renderProps) { store.dispatch(fetchActionCreator()) .then(_ => { const html = renderToString( <Provider store={store}> <RoutingContext {...renderProps} /> </Provider> ); res.end(renderFullPage(html, store.getState())); }); } else { res.status(404).send('Not found') } }) }) match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { import routes from './routes' <RoutingContext {...renderProps} /> Browser SPA <Route path="/" component={Container} > <IndexRoute component={App} /> <Route path=“path/:other” component={Other} /> </Route>
– reactjs/react-router “Knowing what code should run on the server
and on the client is important to using React in a universal app.”
Client or Server • componentDidMount() Invoked once, only on the
client (not on the server) • <Link /> or <a /> • isomorphic-fetch
Server Consistent function renderFullPage(html, initialState) { return ` <!DOCTYPE html>
... <div id=“root”>${html}</div> ... ` } Browser document.addEventListener('DOMContentLoaded', () => { render(<App />, document.getElementById('root')); }); <div id=“root”></div> <div id=“root”>${html}</div> document.getElementById('root')
Demo https://src.coding.net/