【发布时间】:2017-05-11 23:14:26
【问题描述】:
我正在尝试使用 redux-thunk 和 axios 调用 ajax。我想从 json 文件中获取数据
简单的方法(按钮点击调用这样的)
axios.get('data.json').then((data)=>{
console.log(data);
})
但我想使用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'))
【问题讨论】:
标签: reactjs react-router react-redux redux-thunk axios