react-router-redux打破了我的应用程序状态

时间:2016-02-10 07:52:14

标签: javascript reactjs ecmascript-6 react-router redux

我尝试在我的应用程序中设置react-router-redux,如here所示,但它破坏了我的状态。

这是我的商店设置:

import { createStore, applyMiddleware } from 'redux'
import { combineReducers } from 'redux'
import thunk from 'redux-thunk'
import { syncHistory, routeReducer } from 'react-router-redux'
import rootReducer from '../reducers'
import Immutable, {Map} from 'immutable'
[Other imports]

const middleware = [X,Y]

const reducer = combineReducers(Object.assign({}, rootReducer, {
  routing: routeReducer
}));

export default function configureStore(initialState, history) {

   const reduxRouterMiddleware = syncHistory(history);
   middleware.push(reduxRouterMiddleware);

   const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);

   const store = createStoreWithMiddleware(reducer, initialState);     

   return store

}

这是我的reducers / index.js:

import { combineReducers } from 'redux'
import A from './A'
import B from './B'
import C from './C'
...

const rootReducer = combineReducers({
  A,
  B,
  C,
  ...
})

export default rootReducer

当我在我的应用程序中调试我的store.getState()时,我得到:只有一个routing.location树。

only routing.location

如果在创建商店时使用“rootReducer”而不是“reducer”,我会得到正常的状态树(A,B,C ......)

no routing.location

但当然我不再获得我感兴趣的routing.location部分......

我做错了什么?

谢谢大家!

2 个答案:

答案 0 :(得分:1)

我认为这是因为您在自己的Reducer上调用了combineReducer,然后再次在routing减速器中进行合并。我只是从你自己的reducer中导出一个对象,然后进行一次combineReducer调用,在那里你Object.assign路由缩减器。

答案 1 :(得分:1)

我认为问题在于:

const reducer = combineReducers(Object.assign({}, rootReducer, {
  routing: routeReducer
}));

rootReducer不是普通对象,而是由combineReducer方法返回的函数,如下所示:

function combination() {
    var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
    var action = arguments[1]; ...
}

所以你要做的是将一个对象与一个函数合并,该函数只返回该对象。在你的情况下只有“路由”。