21.详情页面布局及异步数据获取19-07-04

代码见https://gitee.com/XiaoKunErGe/JianShu.git历史版本第22次提交。
一.到page目录下的detail目录中创建store,并在store目录下创建actionCreators、constants、index、reducer文件。
到创建的index文件夹下将这些文件导出

import reducer from './reducer';
import * as actionCreators from './actionCreators';
import * as constants from './constants';
export { reducer,actionCreators,constants };

并导入到最外层的store文件夹下的reducer中

import {reducer as detailReducer} from '../pages/detail/store';
const reducer = combineReducers({
  header: headerReducer,
  home: homeReducer,
  detail: detailReducer
})

二.到detail的index下创建页面组件

import { DetailWrapper,Header,Content } from './style'

        

style.js

import styled from 'styled-components';
export const DetailWrapper = styled.div`
  overflow: hidden;
  width: 960px;
  margin: 0 auto;
  padding-bottom: 100px;
`;
export const Header = styled.div`
  margin: 50px 0 20px 0;
  line-height: 44px;
  font-size: 34px;
  color: #333;
  font-weight: bold;
`;
export const Content = styled.div`
  color: #2f2f2f;
  img {
    width: 100%; 
  }
  p {
    margin: 25px 0;
    font-size: 16px;
    line-height: 30px;
  }
  b {
    font-weight: bold;
  }
`;

三.到detail的reducer中,添加初始数据

import { fromJS } from 'immutable';
const defaultState = fromJS({
  title: '我是title',
  content: '我是content'
});

export default (state = defaultState, action) => {
  switch(action.type){
    default:
      return state
  }
};

到detail的index中使用redux获取数据

import { connect } from 'react-redux';
const mapStateToProps = (state)=>({
  title: state.getIn(['detail','title']),
  content: state.getIn(['detail','content'])
});
const mapDispatchToProps = (dispatch)=>({
});
export default connect(mapStateToProps,mapDispatchToProps)(Detail);

添加生命周期函数,在函数中获取线上数据,并通过dispatch方法把数据传给store

componentDidMount(){
    this.props.getDetail();
  }
const mapDispatchToProps = (dispatch)=>({
  getDetail(){
    dispatch(actionCreators.getDetail())
  }
});

四.到actionCreators中获取,使用axios获取数据,并使用dispatch传递给reducer
constants.js

export const CHANGE_DETAIL = 'detail/CHANGE_DETAIL';

actionCreators.js

import axios from 'axios';
 import *as constants from './constants';

const changeDetail = (title,content)=>({
  type: constants.CHANGE_DETAIL,
  title,
  content
});

export const getDetail = () => {
  return (dispatch)=> {
    axios.get('/api/detail.json')
      .then((res)=>{
        const result = res.data.data;
        dispatch(changeDetail(result.title, result.content));
      })
  }
};

reducer将数据传给store并显示

import { fromJS } from 'immutable';
import {CHANGE_DETAIL} from "./constants";

const defaultState = fromJS({
  title: '',
  content: ''
});
export default (state = defaultState, action) => {
  switch(action.type){
    case CHANGE_DETAIL:
      return state.merge({
        title: action.title,
        content: action.content
      });
    default:
      return state
  }
};

你可能感兴趣的:(21.详情页面布局及异步数据获取19-07-04)