前面我们已经把详情页面数据放在了 redux 中,现在,我们要把redux 中内容通过ajax 方式异步获取。
首先,我们在 src/pages/detail 下的 index 中写一下,组件的生命周期函数 componentDidMount ,在这儿发送ajax 请求。如下。
我们发送一个actionCreators.getDetail() action(函数),在这个action 中我们来写异步的请求。
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { DetailWrapper,
Header,
Content
} from './style';
import { actionCreators } from './store';
class Detail extends Component {
render () {
const { title, content, getDeaile } = this.props;
return (
<DetailWrapper>
<Header>
{ title }
</Header>
<Content dangerouslySetInnerHTML={{__html: content}}>
</Content>
</DetailWrapper>
)
}
componentDidMount () {
getDeaile();
}
}
const mapState = (state) => {
return {
title: state.get("detail").get("title"),
content: state.get("detail").get("content")
}
}
const mapDispatch = (dispatch) => {
return {
getDeaile () {
dispatch(actionCreators.getDetail());
}
}
}
export default connect(mapState, mapDispatch)(Detail);
下面我们来写 actionCreators.js 中的内容,如下。
import axios from 'axios';
import * as actionTypes from './actionTypes';
const chanegDetail = (title, content) => {
return {
type: actionTypes.CHANGE_DETAIL,
title,
content
}
}
export const getDetail = () => {
return (dispatch) => {
axios.get('/api/detail.json').then((res) => {
const result = res.data.data;
const action = chanegDetail(result.title, result.content);
dispatch(action);
})
}
}
最后,我们再在 src/pages/detail/store 下的reducer 中处理这个action ,如下。
import axios from 'axios';
import * as actionTypes from './actionTypes';
const chanegDetail = (title, content) => {
return {
type: actionTypes.CHANGE_DETAIL,
title,
content
}
}
export const getDetail = () => {
return (dispatch) => {
axios.get('/api/detail.json').then((res) => {
const result = res.data.data;
const action = chanegDetail(result.title, result.content);
dispatch(action);
})
}
}