【问题标题】:In Redux, where does the state actually get stored?在 Redux 中,状态实际存储在哪里?
【发布时间】:2018-03-05 05:52:31
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    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 中的 state 只是一个持久存在内存中的变量,因为它被所有 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 值,而不仅仅是一个对象。将它作为一个对象(或像数组这样的特殊对象)通常是最有意义的,因为这允许更灵活的数据结构(但如果您愿意,可以将状态设置为例如数字) .

    查看实际的 Redux implementation 了解更多详情。

    如果您希望状态保存在 cookie 或 localStorage 中,您可以enhance the store 这样,除了更新内存中的状态之外,它还会保存到您想要的存储中(并在存储已初始化)

    【讨论】:

    • 内存?是 RAM 内存吗?
    • 是的。在内存中
    • 试图找出他们正在做的事情。你能帮我找到吗?
    • 状态点是与世界其他地方隔离的(查看Module Pattern),并且只能使用通过纯函数(动作调度程序)公开的严格 API 进行更改。这意味着状态是本地化和操纵的,没有副作用。如果您只是将数据传递给所有组件,那么任何组件都可以随时更改该状态,这会产生难以调试的问题和难以推理的代码(状态更改可能随时发生在任何地方)。
    • @JamesBarrett 看起来 Redux 代码库已转换为 TypeScript,它破坏了我所有的链接(指向 .js 文件的链接)。现在应该更新了。
    【解决方案2】:

    状态存储在 redux-store 中。 Redux Store 是一个可以在任何地方/任何组件访问的全局存储。

    让我们考虑一个使用第三方 API 获取数据索引的示例。下面的 sn-p 使用了componentWillMount,它将使用 redux 操作触发 fetch 调用。

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import { fetchDataFromUrl } from '../actions/index.js';
    
    
    class Indexdata extends Component {
    
    
      constructor(props){
        super(props);
        this.state = {
          text: ''
        }
      }
    
    
      componentWillMount(){
        let thisVal = this;
          thisVal.props.fetchIndexofData()
      }
    
      componentWillReceiveProps(nextProps){
        this.setstate({
          text: nextProps.indexData.text
        })
      }
    
      render(){
        return(
          <div>
            <Navbar />
            <h2 className="prescription-index-title">Index of Data</h2>
          </div>
        )
      }
    }
    
    function mapStateToProps(state){
      return{
        indexData: state.fetchedData
      }
    }
    
    function mapDisptachToProps(dispatch){
      return {
        fetchIndexofData: () => dispatch(fetchDataFromUrl(access_token))
      };
    };
    
    export default connect(mapStateToProps, mapDisptachToProps)(IndexData);
    

    上面的 sn-p 将使用 redux 操作获取数据索引。下面的代码是一个redux动作,

    export function fetchDataFromUrl(){
      return(dispatch) => {
        const base_url = "https://api_serving_url.com"
        fetch(base_url, {
          method: 'GET'
        })
        .then(response => response.json())
        .then(data => {
          dispatch({
            type: "INDEX_DATA",
            data: data
          })
        })
      }
    }
    

    Redux action 会将数据分派到 reducer,其中 state 将在 redux store 中初始化。下面的代码sn -p就是redux-reducer

    export function fetchedData(state = [], action) {
      switch(action.type) {
        case "INDEX_DATA":
          return action.data;
        default:
          return state; 
      }
    }
    

    存储在 redux store 中的状态将使用函数mapStateToProps 进行映射,在上述组件中实现。现在您可以使用相应组件中的道具访问状态。 Lifecyclehook componentWillReceiveProps 将能够获取状态存储的 redux 存储。

    您可以通过在任何组件中使用store.getState() 来访问状态。使用reducer 状态的唯一缺点是它会在您刷新组件/应用程序时重置状态。通过Reducer Store 获取更多信息。

    【讨论】:

    • 所以现在,状态存储在 redux 存储中。 redux store 存储在哪里?
    • Redux 存储存储在您的浏览器存储中。这就是为什么在刷新页面时,最终会重新渲染您的组件,从而使您的 redux-store 重置。
    • 否 @ThananjayaChakravarthy,它存储在 RAM 中。如果不想刷卡,可以使用 redux-persist github.com/rt2zz/redux-persist。
    猜你喜欢
    • 2016-08-15
    • 2020-01-10
    • 2022-08-15
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 2021-09-27
    • 2012-04-07
    • 2011-10-26
    相关资源
    最近更新 更多