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
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) I know you can use something like createStore(rootReducer, initialState)
.
const store = createStore(
rootReducer,
initialState
)
const initialState = {
text: "Initial Global State!"
}
(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 ={}
Resulting global store:
(1) outputs {text: "Initial Global State!"}
(2) outputs {text: "Initial Reducer State!"}
Why does #2 work the way it does?
When and where does it get set?
[answer comes from me playing around with redux and getting advice from a senior react-redux dev, Andrew Dushane]
When a store is created through redux, every reducer automatically gets triggered one time
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}"
In redux's documentation, near the end of the file, there is a dispatch({ type: ActionTypes.INIT })
See here https://github.com/reduxjs/redux/blob/master/src/createStore.js#L281-L284
Because in example #2,
combineReducers({text: rootReducer})
gets set rootReducer
runs, because every reducer runs one time on store creation "Initial Reducer state!"
text
in ({text: rootReducer
}) captures response {text: "Initial Reducer State!"}
gets stored as global state if you were to set an initialState
on the store, this always runs after all the reducers get dispatched one time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.