我搜索了一些关于这个问题的信息,但发现了非常模糊的答案。在redux中,我们知道状态是作为对象存储的。但这个状态实际上存储在哪里呢?它是否以某种方式保存为我们以后可以访问的文件?据我所知,它不会以 cookie 格式存储或存储在浏览器的本地存储中。
最佳答案
Redux 中的状态存储在内存中, in the Redux store .
这意味着,如果刷新页面,该状态就会被清除。
你可以想象那家商店看起来像这样:
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
}
}
redux 中的状态只是一个保留在内存中的变量,因为它被所有 redux 函数引用(通过 closure )。
以下是正在发生的事情的简化示例:
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
)
此外,声明
In redux, we know that the state is stored as an object.
不正确。 redux 中的状态可以是任何有效的 javascript 值,而不仅仅是一个对象。它通常最有意义的是它是一个对象(或像数组这样的特殊对象),因为它允许更灵活的数据结构(但如果你愿意,你可以让状态只是一个数字) .
查看实际的 Redux implementation了解更多详情。
如果您希望状态保留在 cookie 或 localStorage 中,您可以 enhance the store这样,除了更新内存中的状态之外,它还会保存到您所需的存储(并在存储初始化时从该存储加载)
关于javascript - 在 Redux 中,状态实际上存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49104247/