2017-08-26 93 views
2

我使用减速器和增强器功能创建了一个redux存储器。Redux:通过组合减速器和存储增强器的预装状态

const store = createStore(rootReducer, compose(
     applyMiddleware(thunk), 
     DevTools.instrument() 
    )) 

rootReducer使用combineReducers来创建单根缩减器。我想在商店内初始化窗口的位置值,所以我想是这样的:

const initialWindowLocation = window.location.hostname 
const store = createStore(rootReducer, initialWindowLocation, compose(
     applyMiddleware(thunk), 
     DevTools.instrument() 
)) 

我连店里的Redux的形式,我能够通过mapStateToProps 但我抓住所有的减速值试图从redux createStore中访问一个简单的字符串值(ieinitialWindowLocation)。是否有一些我缺少的窍门?

另外,如果我尝试,我得到了意想不到的键错误:

Unexpected key found in previous state received by the reducer. 

对这个有什么想法?提前致谢。

回答

1

作为每redux docs here

createStore(减速机,[preloadedState],[增强剂])

[preloadedState] (any): The initial state. You may optionally specify it to hydrate the state from the server in universal apps, or to restore a previously serialized user session. If you produced reducer with combineReducers, this must be a plain object with the same shape as the keys passed to it. Otherwise, you are free to pass anything that your reducer can understand.

其更好地创造一个更减速器。

const window = (state = window.location.hostname,action)=>state; 

并将其添加到combineReducers列表中。

编辑:

I'm wondering why passing in the plain object as the second argument to the createStore doesn't work

假设你rootReducer这个样子的一个。

const window = (state = { location: "test" }, action) => state; 
const user = (state = "", action) => state; 
const rootReducer = combineReducers({ window, user }); 

当你说“在平原对象传递作为第二个参数createStore”, 它的手段,preloadedstate应该符合减速默认状态。

preloadedstate = { user: [], window: { location: "windowone" }}`

const store = createStore(rootReducer, { user: [], window: { location: "windowone" } }, applyMiddleware(...middleWare)); 

否则,你会得到一个错误Unexpected key found in previous state received by the reducer.作为还原剂定义没有这样的关键。

+0

感谢和同意,我阅读了文档,但我对这条线感到困惑:如果您使用combineReducers制作reducer,则它必须是与传递给它的按键形状相同的普通对象。从我的理解,我认为createStore的preloadedstate的第二个参数必须是一个普通的对象,但基于所有的例子看起来像第二个参数应该跳过,值应该传递给combineReducers,我想知道为什么通过作为createStore的第二个参数的普通对象不起作用。请你解释一下 – HitRefresh

+0

@ pink612检查编辑 –

+0

找到了你!非常感谢你 – HitRefresh