如何在反应中从文件中加载数据?
Posted
技术标签:
【中文标题】如何在反应中从文件中加载数据?【英文标题】:how to load data from file in react? 【发布时间】:2017-05-12 09:24:03 【问题描述】:我正在尝试使用redux-thunk
从文件中加载数据,请告诉我如何调用load
函数
我想从 react-thunk 的文件中获取数据
这是我的代码
https://plnkr.co/edit/bcGI7cHjWVtlaMBil3kj?p=preview
const thunk = ReduxThunk.default;
const abc= (state=,action) =>
console.log('in redux', action.type)
switch(action.type)
case 'GET_DATA':
return action
default :
return state;
const createStore,bindActionCreators ,applyMiddleware =Redux;
const Provider,connect =ReactRedux;
const store = createStore(abc,
applyMiddleware(thunk)
);
class First extends React.Component
constructor (props)
super(props);
getDate()
this.props.getData();
render()
return (
<div>
<button onClick=this.getDate.bind(this)>GET DATA</button>
</div>
)
const actions =
getData: () =>
return
type: 'GET_DATA',
;
function loadSuccess(data)
return type :"LOAD_DATA",data
function load()
return dispatch =>
return axios.get('data.json').then(data=>
return dispatch(loadSuccess(data));
)
const AppContainer = connect(
function mapStateToProps(state)
return
digit: state
;
,
function mapDispatchToProps(dispatch)
return bindActionCreators(actions, dispatch);
)(First);
ReactDOM.render(
<Provider store=store>
<AppContainer/>
</Provider>
,document.getElementById('root'))
【问题讨论】:
【参考方案1】:Redux Thunk 中间件允许您编写返回函数而不是动作的动作创建器。 thunk 可用于延迟动作的分派,或仅在满足特定条件时分派。内部函数接收 store 方法 dispatch 和 getState 作为参数。
加载操作创建者应该返回一个执行数据异步请求的函数。当对来自文件的数据的异步请求得到解决时,thunk 可以调度更新存储的操作:
const createStore, bindActionCreators, applyMiddleware = Redux;
const Provider, connect = ReactRedux;
const thunk = window.ReduxThunk.default;
const abc = (state=, action) =>
switch (action.type)
case 'SET_DATA':
return action.payload;
default:
return state;
;
;
const store = createStore(abc, applyMiddleware(thunk));
class First extends React.Component
constructor (props)
super(props);
this.getData = this.getData.bind(this);
getData()
this.props.load();
render()
return (
<div>
<button onClick=this.getData>GET DATA</button>
<pre>JSON.stringify(this.props.data)</pre>
</div>
);
const actions =
load: () =>
return (dispatch) =>
return axios.get('data.json').then((response) =>
dispatch(
type: 'SET_DATA',
payload: response.data,
);
);
;
;
const mapStateToProps = (state) => (
data: state
);
const mapDispatchToProps = (dispatch) => (
load: bindActionCreators(actions.load, dispatch),
);
const AppContainer = connect(mapStateToProps, mapDispatchToProps)(First);
ReactDOM.render(
<Provider store=store>
<AppContainer/>
</Provider>
,document.getElementById('root'));
https://embed.plnkr.co/mJQtEye8SOtXna26XEf7/
【讨论】:
以上是关于如何在反应中从文件中加载数据?的主要内容,如果未能解决你的问题,请参考以下文章