【问题标题】:Different ways of initializing a react redux store's initial global state?初始化 react redux store 的初始全局状态的不同方法?
【发布时间】:2019-09-10 11:29:40
【问题描述】:

初始化 react redux 存储的初始全局状态有哪些不同的方法?我看到 两种 这个 redux 可以设置初始全局状态的方式

假设我们有一个 reducer,所有的 javascript 都在一个文件中。

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) 之类的东西。

const store = createStore(
  rootReducer,
  initialState
)

const initialState = {
  text: "Initial Global State!"
}

(2) 但是,我注意到一些 repos 将 initialState 设置为空白对象,但 redux 存储显示全局状态已被填充。来自此 stackoverflow 帖子的示例: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 会这样工作?

何时何地设置?

【问题讨论】:

    标签: javascript reactjs redux react-redux store


    【解决方案1】:

    [答案来自我玩弄 redux 并从高级 react-redux 开发人员 Andrew Dushane 那里得到建议]

    当通过 redux 创建 store 时,每个 reducer 都会自动触发一次

    在创建商店时调度了一个操作。这就是每个组合 reducer 中提供的初始状态如何在 store 中初始化的方式。如果您检查 redux 开发工具,您会看到调度的第一个操作是 "@@redux/INIT{something}"

    在redux的文档中,靠近文件末尾,有一个dispatch({ type: ActionTypes.INIT })

    请看这里https://github.com/reduxjs/redux/blob/master/src/createStore.js#L281-L284

    TLDR

    因为在示例 #2 中,

    • 商店已创建
    • combineReducers({text: rootReducer}) 被设置
    • rootReducer 运行,因为每个 reducer 在 store 创建时运行一次
    • 默认返回值,在本例中为"Initial Reducer state!"
    • text in ({text: rootReducer}) 捕获响应
    • {text: "Initial Reducer State!"} 被存储为全局状态

    最后说明

    如果你要在 store 上设置一个 initialState,这总是在所有 reducer 被调度一次之后运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2016-09-22
      • 1970-01-01
      • 2016-02-18
      • 2019-03-12
      • 2019-01-04
      相关资源
      最近更新 更多