redux发送异步请求
1、initialState中初始化异步请求的数据
在reducers.js文件中进行如下操作:
const initialState = {
number: 0,
banners:[]
}
2、将数据进行映射
在Profile/index.js中进行:
const mapStateToProps = state => {
return {
banners: state.banners
}
}
3、ComponentDidMount中调用映射的方法,这个方法中调用dispatch(action)
const mapDispatchToProps = dispatch => {
return {
getProfileBannerData() {
// 这里传入一个异步函数,注意:不能是getBannerAction()
dispatch(getBannerAction);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile)
注意:为什么dispatch能派发函数?
答:createStore时传入一个中间件(如redux-thunk)来帮助派发函数。
在store/index.js中
import { createStore, applyMiddleware } from 'redux';
import reducer from './reducers';
import thunkMiddleware from 'redux-thunk';
const enhancer = applyMiddleware(thunkMiddleware)
const store = createStore(reducer, enhancer);
4、调用dispatch(action),其中action是个函数
其中getBannerAction定义在actionCreators.js中
export const getBannerAction = (dispatch, getState) => {
axios({
url:"http://123.207.32.32:8000/home/multidata"
}).then(res => {
const banners = res.data.data.banner.list
console.log(banners)
dispatch(changeBannersAction(banners))
})
}
getBannerAction函数中通过axios获取数据,之后调用dispatch(changedataAction)
export const changeBannersAction = banners => ({
type: CHANGE_BANNERS,
banners
})
5、reducer通过监听changeBannersAction,获得数据,从而变更state
reducers.js
function reducer(state = initialState, action) {
switch(action.type) {
case ADD_NUMBER:
return {...state, number: state.number + action.num}
case SUB_NUMBER:
return {...state, number: state.number - action.num}
case CHANGE_BANNERS:
return {...state, banners: action.banners}
default:
return state;
}
}
6、组件进行render()
import React, { Component } from 'react';
// import store from '../store'
import { connect } from 'react-redux'
import { getBannerAction } from "../store/actionCreator"
class Profile extends Component {
componentDidMount(){
this.props.getProfileBannerData()
}
render() {
return (
<div>
<h2>Profile</h2>
<ul>
{ this.props.banners.map((item, index) => {
return <li key = { index }>{ item.title }</li>
}) }
</ul>
</div>
);
}
}
const mapStateToProps = state => {
return {
banners: state.banners
}
}
const mapDispatchToProps = dispatch => {
return {
getProfileBannerData() {
// 这里传入一个异步函数,注意:不能是getBannerAction()
dispatch(getBannerAction);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile)