我搜索了一下这个问题,但找到了非常模糊的答案.在redux中,我们知道状态存储为对象.但这种状态实际上存储在哪里呢?它是否以某种方式保存为我们以后可以访问的文件?我所知道的是,它不会以cookie格式存储,也不会存储在浏览器的本地存储中.
我搜索了一下这个问题,但找到了非常模糊的答案.在redux中,我们知道状态存储为对象.但这种状态实际上存储在哪里呢?它是否以某种方式保存为我们以后可以访问的文件?我所知道的是,它不会以cookie格式存储,也不会存储在浏览器的本地存储中.
Redux中的状态存储在内存in the Redux store中.
这意味着,如果刷新页面,该状态将被清除.
你可以想象那家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
)
此外,声明
在redux中,我们知道状态存储为对象.
这是不对的.redux中的状态可以是任何有效的javascript值,而不仅仅是一个对象.它通常是一个对象(或像数组这样的特殊对象)最有意义,因为这允许更灵活的数据 struct (但如果你想的话,可以将状态设置为一个数字).
查看实际的Redux implementation了解更多细节.
如果希望状态在cookie或localStorage中保持不变,那么除了在内存中更新状态外,它还将保存到所需的存储中(并在存储初始化时从该存储中加载)