Skip to content

Instantly share code, notes, and snippets.

@banyudu
Last active July 9, 2019 07:03
Show Gist options
  • Save banyudu/0a20de048ad677dfb9918d8e6c434518 to your computer and use it in GitHub Desktop.
Save banyudu/0a20de048ad677dfb9918d8e6c434518 to your computer and use it in GitHub Desktop.
dva.js prerender
///<reference path="./global.d.ts" />
import React from 'react'
import dva from 'dva'
import createHistory from 'history/createBrowserHistory'
import createLoading from 'dva-loading'
import { Router, Route } from 'dva/router'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
import _ from 'lodash'
import { render } from 'react-snapshot'
const initialStateLocalStorageKey = 'initial-state'
let initialState = {}
if (window.localStorage) {
const data = window.localStorage.getItem(initialStateLocalStorageKey)
initialState = data ? JSON.parse(data) : {}
}
const app: any = dva({
initialState,
history: createHistory(),
onStateChange () {
if (window.localStorage) {
window.localStorage.setItem(initialStateLocalStorageKey, JSON.stringify(_.pick(app._store.getState(), [])))
}
}
})
app.use(createLoading())
app.router(
({ history }: any) => {
return (
<Router history={createHistory()}>
<Route path={process.env.PUBLIC_URL + '/'} component={App} />
</Router>
)
}
)
render(app.start()(), document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment