how to set initial state in redux

前端 未结 4 1093
梦如初夏
梦如初夏 2020-12-03 04:07

I\'m trying to figure out how to set an initial state for a store in redux. I\'m using https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.j

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 04:45

    per @ctrlplusb answer, the reason this works is because

    const rootReducer = combineReducers({
      todos: todos,
      visibilityFilter: visibilityFilter
    });
    

    the first todos is a key which sets the second todos as a return value from the reducer. Reducers always run one time upon store creation. This initializes your global store.

    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

    See this question/answer I made on stackoverflow clarifying the response: Different ways of initializing a react redux store's initial global state?

提交回复
热议问题