In Redux, where does the state actually get stored?

后端 未结 2 1555
再見小時候
再見小時候 2020-12-29 04:47

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 so

2条回答
  •  一生所求
    2020-12-29 05:08

    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(
          

    Index of Data

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

提交回复
热议问题