我正在尝试使用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'))
答案 0 :(得分:2)
Redux Thunk中间件允许您编写返回函数而不是动作的动作创建者。 thunk可用于延迟动作的发送,或仅在满足某个条件时发送。内部函数接收存储方法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'));