首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Redux中,状态实际上存储在哪里?

在Redux中,状态实际上存储在哪里?
EN

Stack Overflow用户
提问于 2018-03-05 13:52:31
回答 1查看 15.5K关注 0票数 34

我搜索了一下这个问题,但找到了非常模糊的答案。在redux中,我们知道状态被存储为对象。但是这个状态到底存储在哪里呢?它是不是以某种方式保存为一个文件,以便我们以后可以访问?我所知道的是,它不会以cookie格式或在浏览器的本地存储中存储它。

EN

回答 1

Stack Overflow用户

发布于 2018-03-05 14:29:41

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

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

代码语言:javascript
复制
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);

上面的代码片段将使用redux操作获取数据索引。下面的代码是redux操作,

代码语言:javascript
复制
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操作将数据分派到reducer,在redux存储中初始化状态。下面的代码片段是redux-reducer

代码语言:javascript
复制
export function fetchedData(state = [], action) {
  switch(action.type) {
    case "INDEX_DATA":
      return action.data;
    default:
      return state; 
  }
}

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

您可以通过在任何component.The中使用store.getState()的方式访问状态,使用reducer状态的唯一缺点是,当您刷新组件/应用程序时,它将重置状态。有关更多信息,请访问Reducer Store

票数 -5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49104247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档