问题描述
初始化 react redux store 的初始全局状态有哪些不同的方式?我看到两种这个 redux 可以设置初始全局状态的方式
What are the different ways of initializing a react redux store's initial global state? I see two ways this redux could set an initial global state
假设我们有一个 reducer,所有的 javascript 都在一个文件中.
Let's say we have a single reducer and all the javascript is in one file.
function rootReducer(state = "Initial Reducer State!", action){
switch(action.type) {
case SET_TEXT:
return "Ignore this case statement it won't run"
default:
return state;
}
}
(1) 我知道你可以使用类似 createStore(rootReducer, initialState)
的东西.
(1) I know you can use something like createStore(rootReducer, initialState)
.
const store = createStore(
rootReducer,
initialState
)
const initialState = {
text: "Initial Global State!"
}
(2) 但是,我注意到一些存储库将 initialState
设置为空白对象,但 redux 存储显示已填充全局状态.此 stackoverflow 帖子中的示例:如何在 redux 中设置初始状态
(2) However, I noticed some repos setting an initialState
to a blank object, but the redux store shows a global state has been populated. Example from this stackoverflow post: how to set initial state in redux
const store = createStore(
combineReducers({
text: rootReducer
}),
initialState
)
const initialState ={}
生成的全局存储:
(1) 输出 {text: "Initial Global State!"}
(2) 输出 {text: "Initial Reducer State!"}
为什么#2 的工作方式如此?
Why does #2 work the way it does?
何时何地设置?
推荐答案
[答案来自我玩 redux 并从高级 react-redux 开发者 Andrew Dushane 那里获得建议]
当通过 redux 创建 store 时,每个 reducer 都会自动触发一次
When a store is created through redux, every reducer automatically gets triggered one time
在创建商店时分派了一个操作.这就是在每个组合减速器中提供的初始状态在商店中初始化的方式.如果您检查 redux 开发工具,您将看到调度的第一个操作是 "@@redux/INIT{something}"
There's an action dispatched when the store is created. That's how the initial state supplied in each combined reducer gets initialized in the store. If you check redux dev tools you'll see the first action dispatched is "@@redux/INIT{something}"
在 redux 的文档中,在文件末尾附近,有一个 dispatch({ type: ActionTypes.INIT })
In redux's documentation, near the end of the file, there is a dispatch({ type: ActionTypes.INIT })
见这里https://github.com/reduxjs/redux/blob/master/src/createStore.js#L281-L284
因为在示例#2 中,
- 商店已创建
combineReducers({text: rootReducer})
设置rootReducer
运行,因为每个 reducer 在创建 store 时运行一次- 默认返回值,在这种情况下
Initial Reducer state!"
text
在({text: rootReducer
}) 中捕获响应{text: "Initial Reducer State!"}
被存储为全局状态
- store is created
combineReducers({text: rootReducer})
gets setrootReducer
runs, because every reducer runs one time on store creation- Default return value is made, in this case
"Initial Reducer state!"
text
in({text: rootReducer
}) captures response{text: "Initial Reducer State!"}
gets stored as global state
如果你要在 store 上设置一个 initialState
,这总是在所有 reducer 被分派一次后运行.
if you were to set an initialState
on the store, this always runs after all the reducers get dispatched one time.
这篇关于初始化 react redux store 的初始全局状态的不同方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!