In Redux, where does the state actually get stored

2019-04-19 00:26发布

问题:

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.

回答1:

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
  }
}

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
)

Furthermore, the statement

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

Isn't correct. State in redux can be any valid javascript value, not just an object. It just makes 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).

Check out the actual Redux implementation for more details.

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 app loads)



回答2:

States are stored in redux-store. Redux Store is a global store which can be accessed anywhere/any components.

Let consider an example of getting Index of data using third party API. The following snippet uses componentWillMount which will trigger a fetch call using redux action.

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);

The above snippet will fetch index of data using a redux action. The below code is a redux action,

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 will dispatch data to reducer, where state will be initialized in redux store. The following code snippet is redux-reducer

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

State stored in redux store will be mapped using function mapStateToProps, implemented in the above component. Now you can access the state using props in the respective component. Lifecyclehook componentWillReceiveProps will be able to fetch the state stored redux store.

You can access the State by means of using store.getState() in any component.The only drawback of using reducer state, is that it will reset the state when you refresh the component/application. Go through Reducer Store , for more information.