gpt4 book ai didi

reactjs - Redux:使用组合的 reducer 和存储增强器传递预加载状态

转载 作者:行者123 更新时间:2023-12-03 13:37:10 27 4
gpt4 key购买 nike

我创建了一个带有 reducer 和增强器功能的 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 createStore 访问一个简单的字符串值(即initialWindowLocation)。我是否缺少一些 redux 技巧?

此外,如果我尝试,我会收到意外的 key 错误:

 Unexpected key found in previous state received by the reducer.

对此有什么想法吗?提前致谢。

最佳答案

根据 redux docs here ,

createStore(reducer, [preloadedState], [enhancer])

[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.

最好再创建一个 reducer 。

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应该与reducer默认状态匹配。

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

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

否则,您将收到错误Unexpected key found in previous state returned by the reducer.,因为reducer中没有定义这样的键。

关于reactjs - Redux:使用组合的 reducer 和存储增强器传递预加载状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45891495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com