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

问题描述:

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

I searched a bit about this question but found very vague answers. In redux, we know that the state is stored as an object. But where is this state stored actually? Is it somehow saved as a file which can be accessed by us later on? What I know is that it does not store it in a cookie format or in the browser's local storage.

Redux中的状态存储在Redux商店的内存中。

The state in Redux is stored in memory, in the Redux store.

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

This means that, if you refresh the page, that state gets wiped out.

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

You can imagine that store looking something like this:

function createStore(reducer, initialState) {
  let state = initialState // <-- state is literally stored 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
  }
}

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

The state in redux is just a variable that persists in memory because it is referenced (via closure) by all redux functions.

下面是一个简单的例子:

Here's a simplified example of what is going on:

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
)

Furthermo re,声明

Furthermore, the statement


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

In redux, we know that the state is stored as an object.

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

isn't correct. State in redux can be any valid javascript value, not just an object. It just usually makes the most sense for it to be an object (or a special object like an array) because that allows for a more flexible data structure (but you could make the state just be a number for example, if you wanted to).

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

Check out the actual Redux implementation for more details.

如果您希望状态保留在cookie或localStorage中,您将增强商店,以便在更新内存状态之上,它也将保存到您想要的存储空间(并在初始化存储时从该存储空间加载)

If you want the state to persist in a cookie or localStorage, you would enhance the store such that, on top of updating the state in memory, it will save to your desired storage as well (and load from that storage when the store is initialized)