Different ways of initializing a react redux store's initial global state?

女生的网名这么多〃 提交于 2019-12-08 11:31:55

问题


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?


回答1:


[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

TLDR

Because in example #2,

  • store is created
  • combineReducers({text: rootReducer}) gets set
  • rootReducer 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

Final Notes

if you were to set an initialState on the store, this always runs after all the reducers get dispatched one time.



来源:https://stackoverflow.com/questions/55774622/different-ways-of-initializing-a-react-redux-stores-initial-global-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!