在Redux中,状态实际存储在哪里?

Dhr*_*wha 23 javascript reactjs redux

我对这个问题进行了一些搜索,但发现了很模糊的答案.在redux中,我们知道状态存储为对象.但这个状态实际存储在哪里?它是以某种方式保存为以后可以访问的文件吗?我所知道的是它不会以cookie格式或浏览器的本地存储中存储它.

nem*_*035 27

Redux中的状态存储在Redux存储区的内存中.

这意味着,如果刷新页面,该状态将被清除.

您可以想象商店看起来像这样:

function createStore(reducer, initialState) {
  let state = initialState // <-- state is just stored in a variable that lives in memory

  function getState() {
    return state
  }

  function dispatch(action) {

    state = reducer(state, action) // <-- state gets updated using the returned value from the reducer

    return action
  }

  return {
    getState,
    dispatch
  }
}
Run Code Online (Sandbox Code Playgroud)

redux中的状态只是一个存储在内存中的变量,因为它被所有redux函数引用(通过闭包).

这是一个简单的例子:

function example() {
  let variableAvailableViaClosure = 0
  
  function incrementTheClosureVariable() {
    variableAvailableViaClosure += 1
  }

  function getTheClosureVariable() {
    return variableAvailableViaClosure
  }

  return {
    incrementTheClosureVariable,
    getTheClosureVariable
  }
}

let data = example()

// at this point example is finished
// but the functions it returned
// still have access to the (internal) variable via closure

console.log(
  data.getTheClosureVariable() // 0
)

data.incrementTheClosureVariable()

console.log(
  data.getTheClosureVariable() // 1
)
Run Code Online (Sandbox Code Playgroud)

此外,声明

在redux中,我们知道状态存储为对象.

不对.redux中的状态可以是任何有效的javascript值,而不仅仅是一个对象.它最有意义的是它成为一个对象(或像数组一样的特殊对象),因为它允许更灵活的数据结构(但是如果你愿意的话,你可以使状态只是一个数字).

查看实际的Redux 实现以获取更多详细信息.

如果您希望状态持久存在于cookie或localStorage中,您可以增强存储,以便在更新内存中的状态之后,它也将保存到您想要的存储(并在应用程序加载时从该存储加载)

  • 是。在RAM中 (3认同)
  • 记忆?是RAM内存吗? (2认同)
  • 状态点是与世界其他地方封闭的(请检阅[模块模式](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript)),并且只能使用通过纯函数(动作分派器)。这意味着状态是本地化的,没有副作用。如果您只是将数据传递给所有组件,那么任何组件都可以随时更改该状态,从而产生难以调试的问题和难以推理的代码(状态更改可以随时随地发生)。 (2认同)