reducer與按需加載組件的時候,一併加載對應的state,具體流程就很少說了,看代碼!javascript
import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' export const makeRootReducer = asyncReducers => { return combineReducers({ routing: routerReducer, ...asyncReducers }) } export const injectReducer = (store, {key, reducer}) => { if(!store.asyncReducers[key]) { store.asyncReducers[key] = reducer; store.replaceReducer(makeRootReducer(store.asyncReducers)); } }
import { applyMiddleware, compose, createStore, combineReducers } from 'redux' import { routerMiddleware } from 'react-router-redux' import thunkMiddleware from 'redux-thunk' import reducer, { makeRootReducer } from './reducer' export default (initialState = {}, history) => { const middleware = [thunkMiddleware, routerMiddleware(history)]; const enhancers = []; const store = createStore( makeRootReducer(), initialState, compose( applyMiddleware(...middleware), ...enhancers ) ); return store; }
import React, { Component } from 'react' import { Router, Route, Redirect } from 'react-router' const moduleRoute = require.context('../view', true, /router$/) //獲取view視圖下,全部router文件 const router = store => { return <Router> <Route path="/"> { moduleRoute.keys().map(key => { return moduleRoute(key).default(store) }) } <Redirect from='*' to='/' /> </Route> </Router> } export default router
import ReactDOM from 'react-dom' import { Router, hashHistory } from 'react-router' import React from 'react' import { Provider } from 'react-redux' import { syncHistoryWithStore } from 'react-router-redux' import createStore from '...上面的store' import router from '...上面的router' const store = createStore({}, hashHistory); store.asyncReducers = {}; const history = syncHistoryWithStore(hashHistory, store); ReactDOM.render(( <Provider store={store}> <Router history={history}> { router(store) } </Router> </Provider> ), document.getElementById("root"))
在view層級下建立一個test文件夾來編輯一下流程
java
在test/ index.jsx 中簡單編輯下react
import React, { Component } from 'react' import { connect } from 'react-redux' class Test extends Component { render() { const { value } = this.props; return <h1>{ value }</h1> } } const mapStateToProps = state => { return { ...state.test } } const mapDispathToProps = dispatch => { return { // } } export default connect(mapStateToProps, mapDispathToProps)(Test);
reducerwebpack
const initState = { value: 'value' } export default (state = initState, action) => { return state; }
routerweb
import { Route } from 'react-router' import { injectReducer } from '...最上面定義的reducer' export default store => { return <Route path='test' getComponent={(nextState, cb) => { import('../'/* webpackChunkName: 'Test' */) .then(module => { injectRoducer(store, {key: test, reducer: require('../redux/reducer')}); cb(null, module.default); }) } }/> }
執行,在未加載該頁面以前,store.state = { routing… };
進入test頁面的時候, store.state = { routing…, test: { value: ‘value’ } }redux