我搜索了一下这个问题,但找到了非常模糊的答案.在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中保持不变,那么除了在内存中更新状态外,它还将保存到所需的存储中(并在存储初始化时从该存储中加载)

Reactjs相关问答推荐

在此上下文中如何在缓冲(隐藏)视频和渲染视频之间切换?

使用useEffect挂钩获取数据

NextJs Form不允许我输入任何输入,

Reaction-路由v6动态路径RegExp

如何使数据库数据在第一次呈现时显示?

错误:操作必须是普通对象.使用自定义中间件进行异步操作. Redux/工具包

滚动视图样式高度没有任何区别

找不到名称setCometChat

如何在react 中过滤数组的数组?

在 React 中使用forwardRef时无法声明自定义属性

如何管理组件列表的复杂状态? (Nextjs/ReactJS)

解决在React测试库中的act()警告

如何在 React 过滤器中包含价格过滤器逻辑?

React - 将一个充满空值的无限大小的数组存储在 ref 中是否可以,或者我应该重置数组吗?

Redux Toolkit 配置,是否适用于全栈应用程序?

下一次导出:未捕获的语法错误:标识符注册表已被声明

我正在try 使用 cypress 测试我的下拉列表,它 Select 值但不提交它们(手动工作)

加密 Django Rest Framework API 响应 + 解密响应应用程序中的响应

如何在 v6.4 中将 Auth0 提供程序与新的 createBrowsereRouter 一起使用?

在react 路由dom版本6中的组件内添加路由