我搜索了一下这个问题,但找到了非常模糊的答案。在redux中,我们知道状态被存储为对象。但是这个状态到底存储在哪里呢?它是不是以某种方式保存为一个文件,以便我们以后可以访问?我所知道的是,它不会以cookie格式或在浏览器的本地存储中存储它。
发布于 2018-03-05 14:29:41
状态存储在redux-store中。Redux Store是一个全局存储,可以在任何地方/任何组件访问。
让我们考虑一个使用第三方API获取数据索引的示例。下面的代码片段使用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);
上面的代码片段将使用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操作将数据分派到reducer,在redux存储中初始化状态。下面的代码片段是redux-reducer
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。
https://stackoverflow.com/questions/49104247
复制相似问题