我使用reducer和enhancer函数创建了一个redux存储。
const store = createStore(rootReducer, compose(
applyMiddleware(thunk),
DevTools.instrument()
))
rootReducer使用combineReducers创建单个根reducer。我想在商店中初始化窗口的位置值,所以我尝试了这样的事情:
const initialWindowLocation = window.location.hostname
const store = createStore(rootReducer, initialWindowLocation, compose(
applyMiddleware(thunk),
DevTools.instrument()
))
我将商店连接到redux表单,我可以通过mapStateToProps 获取所有reducer值但是我试图从redux访问一个简单的字符串值(ieinitialWindowLocation) createStore。是否有一些我缺少的减少技巧?
此外,如果我尝试了,我会收到意外的密钥错误:
Unexpected key found in previous state received by the reducer.
对此有何想法?提前谢谢。
答案 0 :(得分:2)
createStore(reducer,[preloadedState],[enhancer])
[preloadedState](any):初始状态。您可以选择将其指定为在通用应用程序中从服务器中保持状态,或者还原以前序列化的用户会话。如果使用combineReducers生成reducer,则它必须是一个普通对象,其形状与传递给它的键相同。否则,您可以自由地传递减速器可以理解的任何内容。
最好再制造一个减速器。
const window = ( state = window.location.hostname,action )=>state;
并将其添加到combineReducers
列表。
编辑:
我想知道为什么传递普通对象作为createStore的第二个参数不起作用
假设你的rootReducer看起来像这样。
const window = (state = { location: "test" }, action) => state;
const user = (state = "", action) => state;
const rootReducer = combineReducers({ window, user });
当你说"传入普通对象作为createStore"的第二个参数时,
它的意思是preloadedstate
应该与reducer默认状态匹配。
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.
,因为在reducers中没有定义此类密钥。