mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
Implement with-redux using _app.js (#4295)
* Simplify redux example * Simplify redux example even more * Remove empty space
This commit is contained in:
parent
6c0091fb7a
commit
0697c289f8
|
@ -41,28 +41,18 @@ now
|
|||
|
||||
## The idea behind the example
|
||||
|
||||
This example is based on [full example](https://github.com/kirill-konshin/next-redux-wrapper) which should probably be used for production. The next.js example with this library can be found [here](https://github.com/zeit/next.js/tree/canary/examples/with-redux-wrapper)
|
||||
This example shows how to integrate Redux in Next.js.
|
||||
|
||||
The reason for this example is to show an easier to follow and extendable way to include Redux in a next.js app.
|
||||
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use redux that also works with Next.js's universal rendering approach.
|
||||
|
||||
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use redux that also works with our universal rendering approach. This is just a way you can do it but it's not the only one.
|
||||
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color (black) than the client one (grey).
|
||||
|
||||
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one.
|
||||
The Redux `Provider` is implemented in `pages/_app.js`. Since the `MyApp` component is wrapped in `withReduxStore` the redux store will be automatically initialized and provided to `MyApp`, which in turn passes it off to `react-redux`'s `Provider` component.
|
||||
|
||||
![](http://i.imgur.com/JCxtWSj.gif)
|
||||
All pages have access to the redux store using `connect` from `react-redux`.
|
||||
|
||||
Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `withRedux.js`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required.
|
||||
On the server side every request initializes a new store, because otherwise different user data can be mixed up. On the client side the same store is used, even between page changes.
|
||||
|
||||
For safety it is recommended to wrap all pages, no matter if they use Redux or not, so that you should not care about it anymore in all child components.
|
||||
|
||||
`withRedux` function accepts `initStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `initStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here.
|
||||
|
||||
To pass the initial state from the server to the client we pass it as a prop called `initialState` so then it's available when the client takes over.
|
||||
|
||||
The trick here for supporting universal redux is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`
|
||||
|
||||
The clock, under `components/Clock.js`, has access to the state using the `connect` function from `react-redux`. In this case Clock is a direct child from the page but it could be deep down the render tree.
|
||||
|
||||
The second example, under `components/AddCount.js`, shows a simple add counter function with a class component implementing a common redux pattern of mapping state and props. Again, the first render is happening in the server and instead of starting the count at 0, it will dispatch an action in redux that starts the count at 1. This continues to highlight how each navigation triggers a server render first and then a client render second, when you navigate between pages.
|
||||
The example under `components/counter.js`, shows a simple incremental counter implementing a common Redux pattern of mapping state to props. Again, the first render is happening in the server and instead of starting the count at 0, it will dispatch an action in redux that starts the count at 1. This continues to highlight how each navigation triggers a server render first and then a client render when switching pages on the client side
|
||||
|
||||
For simplicity and readability, Reducers, Actions, and Store creators are all in the same file: `store.js`
|
||||
|
|
|
@ -1,35 +0,0 @@
|
|||
import React, {Component} from 'react'
|
||||
import { connect } from 'react-redux'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { addCount } from '../store'
|
||||
|
||||
class AddCount extends Component {
|
||||
add = () => {
|
||||
this.props.addCount()
|
||||
}
|
||||
|
||||
render () {
|
||||
const { count } = this.props
|
||||
return (
|
||||
<div>
|
||||
<style jsx>{`
|
||||
div {
|
||||
padding: 0 0 20px 0;
|
||||
}
|
||||
`}</style>
|
||||
<h1>AddCount: <span>{count}</span></h1>
|
||||
<button onClick={this.add}>Add To Count</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const mapStateToProps = ({ count }) => ({ count })
|
||||
|
||||
const mapDispatchToProps = (dispatch) => {
|
||||
return {
|
||||
addCount: bindActionCreators(addCount, dispatch)
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(AddCount)
|
|
@ -1,17 +0,0 @@
|
|||
import Link from 'next/link'
|
||||
import { connect } from 'react-redux'
|
||||
import Clock from './Clock'
|
||||
import AddCount from './AddCount'
|
||||
|
||||
export default connect(state => state)(({ title, linkTo, lastUpdate, light }) => {
|
||||
return (
|
||||
<div>
|
||||
<h1>{title}</h1>
|
||||
<Clock lastUpdate={lastUpdate} light={light} />
|
||||
<AddCount />
|
||||
<nav>
|
||||
<Link href={linkTo}><a>Navigate</a></Link>
|
||||
</nav>
|
||||
</div>
|
||||
)
|
||||
})
|
27
examples/with-redux/components/counter.js
Normal file
27
examples/with-redux/components/counter.js
Normal file
|
@ -0,0 +1,27 @@
|
|||
import React, {Component} from 'react'
|
||||
import { connect } from 'react-redux'
|
||||
import { addCount } from '../store'
|
||||
|
||||
class AddCount extends Component {
|
||||
add = () => {
|
||||
const {dispatch} = this.props
|
||||
dispatch(addCount())
|
||||
}
|
||||
|
||||
render () {
|
||||
const { count } = this.props
|
||||
return (
|
||||
<div>
|
||||
<h1>AddCount: <span>{count}</span></h1>
|
||||
<button onClick={this.add}>Add To Count</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function mapStateToProps (state) {
|
||||
const {count} = state
|
||||
return {count}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps)(AddCount)
|
20
examples/with-redux/components/examples.js
Normal file
20
examples/with-redux/components/examples.js
Normal file
|
@ -0,0 +1,20 @@
|
|||
|
||||
import {connect} from 'react-redux'
|
||||
import Clock from './clock'
|
||||
import Counter from './counter'
|
||||
|
||||
function Examples ({ lastUpdate, light }) {
|
||||
return (
|
||||
<div>
|
||||
<Clock lastUpdate={lastUpdate} light={light} />
|
||||
<Counter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function mapStateToProps (state) {
|
||||
const { lastUpdate, light } = state
|
||||
return { lastUpdate, light }
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps)(Examples)
|
49
examples/with-redux/lib/with-redux-store.js
Normal file
49
examples/with-redux/lib/with-redux-store.js
Normal file
|
@ -0,0 +1,49 @@
|
|||
import App, {Container} from 'next/app'
|
||||
import {Provider} from 'react-redux'
|
||||
import {initializeStore} from '../store'
|
||||
|
||||
const isServer = typeof window === 'undefined'
|
||||
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
|
||||
|
||||
function getOrCreateStore(initialState) {
|
||||
// Always make a new store if server, otherwise state is shared between requests
|
||||
if (isServer) {
|
||||
return initializeStore(initialState)
|
||||
}
|
||||
|
||||
// Store in global variable if client
|
||||
if (!window[__NEXT_REDUX_STORE__]) {
|
||||
window[__NEXT_REDUX_STORE__] = initializeStore(initialState)
|
||||
}
|
||||
return window[__NEXT_REDUX_STORE__]
|
||||
}
|
||||
|
||||
export default (App) => {
|
||||
return class Redux extends React.Component {
|
||||
static async getInitialProps (appContext) {
|
||||
const reduxStore = getOrCreateStore()
|
||||
|
||||
// Provide the store to getInitialProps of pages
|
||||
appContext.ctx.reduxStore = reduxStore
|
||||
|
||||
let appProps = {}
|
||||
if (App.getInitialProps) {
|
||||
appProps = await App.getInitialProps(appContext)
|
||||
}
|
||||
|
||||
return {
|
||||
...appProps,
|
||||
initialReduxState: reduxStore.getState()
|
||||
}
|
||||
}
|
||||
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.reduxStore = getOrCreateStore(props.initialReduxState)
|
||||
}
|
||||
|
||||
render() {
|
||||
return <App {...this.props} reduxStore={this.reduxStore} />
|
||||
}
|
||||
}
|
||||
}
|
17
examples/with-redux/pages/_app.js
Normal file
17
examples/with-redux/pages/_app.js
Normal file
|
@ -0,0 +1,17 @@
|
|||
import App, {Container} from 'next/app'
|
||||
import React from 'react'
|
||||
import withReduxStore from '../lib/with-redux-store'
|
||||
import { Provider } from 'react-redux'
|
||||
|
||||
class MyApp extends App {
|
||||
render () {
|
||||
const {Component, pageProps, reduxStore} = this.props
|
||||
return <Container>
|
||||
<Provider store={reduxStore}>
|
||||
<Component {...pageProps} />
|
||||
</Provider>
|
||||
</Container>
|
||||
}
|
||||
}
|
||||
|
||||
export default withReduxStore(MyApp)
|
|
@ -1,19 +1,20 @@
|
|||
import React from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { initStore, startClock, addCount, serverRenderClock } from '../store'
|
||||
import withRedux from '../utils/withRedux'
|
||||
import Page from '../components/Page'
|
||||
import {connect} from 'react-redux'
|
||||
import {startClock, addCount, serverRenderClock} from '../store'
|
||||
import Examples from '../components/examples'
|
||||
|
||||
class Counter extends React.Component {
|
||||
static getInitialProps ({ store, isServer }) {
|
||||
store.dispatch(serverRenderClock(isServer))
|
||||
store.dispatch(addCount())
|
||||
static getInitialProps ({ reduxStore, req }) {
|
||||
const isServer = !!req
|
||||
reduxStore.dispatch(serverRenderClock(isServer))
|
||||
reduxStore.dispatch(addCount())
|
||||
|
||||
return { isServer }
|
||||
return {}
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
this.timer = this.props.startClock()
|
||||
const {dispatch} = this.props
|
||||
this.timer = startClock(dispatch)
|
||||
}
|
||||
|
||||
componentWillUnmount () {
|
||||
|
@ -22,16 +23,9 @@ class Counter extends React.Component {
|
|||
|
||||
render () {
|
||||
return (
|
||||
<Page title='Index Page' linkTo='/other' />
|
||||
<Examples />
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const mapDispatchToProps = (dispatch) => {
|
||||
return {
|
||||
addCount: bindActionCreators(addCount, dispatch),
|
||||
startClock: bindActionCreators(startClock, dispatch)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRedux(initStore, null, mapDispatchToProps)(Counter)
|
||||
export default connect()(Counter)
|
||||
|
|
|
@ -1,36 +0,0 @@
|
|||
import React from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { initStore, startClock, addCount, serverRenderClock } from '../store'
|
||||
import withRedux from '../utils/withRedux'
|
||||
import Page from '../components/Page'
|
||||
|
||||
class Counter extends React.Component {
|
||||
static getInitialProps ({ store, isServer }) {
|
||||
store.dispatch(serverRenderClock(isServer))
|
||||
store.dispatch(addCount())
|
||||
return { isServer }
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
this.timer = this.props.startClock()
|
||||
}
|
||||
|
||||
componentWillUnmount () {
|
||||
clearInterval(this.timer)
|
||||
}
|
||||
|
||||
render () {
|
||||
return (
|
||||
<Page title='Other Page' linkTo='/' />
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const mapDispatchToProps = (dispatch) => {
|
||||
return {
|
||||
addCount: bindActionCreators(addCount, dispatch),
|
||||
startClock: bindActionCreators(startClock, dispatch)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRedux(initStore, null, mapDispatchToProps)(Counter)
|
|
@ -31,14 +31,17 @@ export const serverRenderClock = (isServer) => dispatch => {
|
|||
return dispatch({ type: actionTypes.TICK, light: !isServer, ts: Date.now() })
|
||||
}
|
||||
|
||||
export const startClock = () => dispatch => {
|
||||
return setInterval(() => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }), 1000)
|
||||
export const startClock = dispatch => {
|
||||
return setInterval(() => {
|
||||
// Dispatch `TICK` every 1 second
|
||||
dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() })
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
export const addCount = () => dispatch => {
|
||||
return dispatch({ type: actionTypes.ADD })
|
||||
}
|
||||
|
||||
export const initStore = (initialState = exampleInitialState) => {
|
||||
export function initializeStore (initialState = exampleInitialState) {
|
||||
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
|
||||
}
|
||||
|
|
|
@ -1,58 +0,0 @@
|
|||
import React from 'react'
|
||||
import { connect, Provider } from 'react-redux'
|
||||
|
||||
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
|
||||
|
||||
// https://github.com/iliakan/detect-node
|
||||
const checkServer = () => Object.prototype.toString.call(global.process) === '[object process]'
|
||||
|
||||
const getOrCreateStore = (initStore, initialState) => {
|
||||
// Always make a new store if server
|
||||
if (checkServer() || typeof window === 'undefined') {
|
||||
return initStore(initialState)
|
||||
}
|
||||
|
||||
// Store in global variable if client
|
||||
if (!window[__NEXT_REDUX_STORE__]) {
|
||||
window[__NEXT_REDUX_STORE__] = initStore(initialState)
|
||||
}
|
||||
return window[__NEXT_REDUX_STORE__]
|
||||
}
|
||||
|
||||
export default (...args) => (Component) => {
|
||||
// First argument is initStore, the rest are redux connect arguments and get passed
|
||||
const [initStore, ...connectArgs] = args
|
||||
|
||||
const ComponentWithRedux = (props = {}) => {
|
||||
const { store, initialProps, initialState } = props
|
||||
|
||||
// Connect page to redux with connect arguments
|
||||
const ConnectedComponent = connect.apply(null, connectArgs)(Component)
|
||||
|
||||
// Wrap with redux Provider with store
|
||||
// Create connected page with initialProps
|
||||
return React.createElement(
|
||||
Provider,
|
||||
{ store: store && store.dispatch ? store : getOrCreateStore(initStore, initialState) },
|
||||
React.createElement(ConnectedComponent, initialProps)
|
||||
)
|
||||
}
|
||||
|
||||
ComponentWithRedux.getInitialProps = async (props = {}) => {
|
||||
const isServer = checkServer()
|
||||
const store = getOrCreateStore(initStore)
|
||||
|
||||
// Run page getInitialProps with store and isServer
|
||||
const initialProps = Component.getInitialProps
|
||||
? await Component.getInitialProps({ ...props, isServer, store })
|
||||
: {}
|
||||
|
||||
return {
|
||||
store,
|
||||
initialState: store.getState(),
|
||||
initialProps
|
||||
}
|
||||
}
|
||||
|
||||
return ComponentWithRedux
|
||||
}
|
Loading…
Reference in a new issue