-
Notifications
You must be signed in to change notification settings - Fork 29.9k
Closed
Description
The example of next.js with redux has repeated codes in every page, but wouldn't it be better to use higher-order component to replace this kind of repeated codes. For example:
next-connect.js:
import React, { Component, PropTypes } from 'react'
import { Provider, connect } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import reducer from './reducer'
let store = null
const wrapWithProvider = (PageComponent) => class extends Component {
static propTypes = {
initialState: PropTypes.object
}
static async getInitialProps (ctx) {
const { req } = ctx
const isServer = !!req
const props = PageComponent.getInitialProps ? await PageComponent.getInitialProps(ctx) : {}
if (isServer && typeof window === 'undefined') {
store = createStore(reducer, {}, applyMiddleware(thunkMiddleware))
props.initialState = store.getState()
}
return props
}
constructor (props) {
super(props)
if (!store) {
store = createStore(reducer, props.initialState, applyMiddleware(thunkMiddleware))
}
}
render () {
return (
<Provider store={store}>
<PageComponent {...this.props} />
</Provider>
)
}
}
export default (mapStateToProps, mapDispatchToProps) => (PageComponent) => {
PageComponent = connect(mapStateToProps, mapDispatchToProps)(PageComponent)
return wrapWithProvider(PageComponent)
}In every page you can easily use next-connect.js and connect to store like using redux normally:
index.js:
import nextConnect from './next-connect'
class Index extends Component {
// ...
render () {...}
}
export nextConnect((state) => state, null)(Index)You can gain the same abilities like with-redux example does but with convenience.
Just a suggestion, feel free to close.
tylersnyder, DCKT, orlin, huzidaha, icflorescu and 2 more
Metadata
Metadata
Assignees
Labels
No labels