我試圖調用AJAX使用redux-thunk
和axios
。我想如何使用`redux-thunk`在反應中調用ajax?
簡單的方法(上按一下按鈕調用這樣)
axios.get('data.json').then((data)=>{
console.log(data);
})
從JSON文件數據的反應,但我想用redux-thunk
。換句話說,我需要訂閱組件,這將使用thunk
發送使用我們可以在這裏使用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 dispatch =>{
return axios.get('data.json');
};
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();
// axios.get('data.json').then((data)=>{
// console.log(data);
// })
}
render(){
return (
<div>
<button onClick={this.getDate.bind(this)}>GET DATA</button>
</div>
)
}
}
const actions = {
getData:() => {
return {
type: 'GET_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'))