## 改造详情页 1. 基于dva数据流改造需要做如下修改 * 增加connect ~~~ @connect(({ demo, loading }) => ({ demo, loading: loading.models.demo, })) @Form.create() class DemoEdit extends PureComponent { } ~~~ * 删掉state,修改componentWillMount,使用dispatch调用数据流进行数据加载 ~~~ componentWillMount() { const { dispatch, match: { params: { id }, }, } = this.props; dispatch({ type: 'demo/fetchDetail', payload: { id }, }); } ~~~ * 修改render下原先state中data的获取,改为从props获取并将data改为detail ~~~ const { demo: { detail }, } = this.props; ~~~ 2. 打开系统,详情页数据加载成功 ![](https://box.kancloud.cn/971fd4c92297606e73b81934a1362d97_1858x1136.png) 3. 附上完整代码 ~~~ import { connect } from 'dva'; import React, { PureComponent } from 'react'; import { Form, Card } from 'antd'; import Panel from '../../../components/Panel'; import styles from '../../../layouts/Sword.less'; const FormItem = Form.Item; @connect(({ demo, loading }) => ({ demo, loading: loading.models.demo, })) @Form.create() class DemoEdit extends PureComponent { componentWillMount() { const { dispatch, match: { params: { id }, }, } = this.props; dispatch({ type: 'demo/fetchDetail', payload: { id }, }); } render() { const { demo: { detail }, } = this.props; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 7 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 12 }, md: { span: 10 }, }, }; return ( <Panel title="查看" back="/platform/demo"> <Form hideRequiredMark style={{ marginTop: 8 }}> <Card title="基本信息" className={styles.card} bordered={false}> <FormItem {...formItemLayout} label="标题"> <span>{detail.title}</span> </FormItem> <FormItem {...formItemLayout} label="日期"> <span>{detail.date}</span> </FormItem> <FormItem {...formItemLayout} label="内容"> <span>{detail.content}</span> </FormItem> </Card> </Form> </Panel> ); } } export default DemoEdit; ~~~ 4. 附上model的完整代码 ~~~ import { message } from 'antd'; import router from 'umi/router'; import { list, detail, submit } from '../services/demo'; export default { namespace: 'demo', state: { data: { list: [], pagination: {}, }, detail: {}, }, effects: { *fetchList({ payload }, { call, put }) { const response = yield call(list, payload); if (response.success) { yield put({ type: 'saveList', payload: { list: response.data.records, pagination: { total: response.data.total, current: response.data.current, pageSize: response.data.size, }, }, }); } }, *fetchDetail({ payload }, { call, put }) { const response = yield call(detail, payload); if (response.success) { yield put({ type: 'saveDetail', payload: { detail: response.data, }, }); } }, *submit({ payload }, { call }) { const response = yield call(submit, payload); if (response.success) { message.success('提交成功'); router.push('/platform/demo'); } }, }, reducers: { saveList(state, action) { return { ...state, data: action.payload, }; }, saveDetail(state, action) { return { ...state, detail: action.payload.detail, }; }, }, }; ~~~ <br> ## 结束语 * 经过整本手册的学习,带领大家由浅入深,见证了一个简单组件到复杂的诞生,也见证了一个增删改查模块经过多次修改越来越精简清晰的过程 * 知识的海洋是无限的,大家若能掌握学习方法,相信以后会对React更加熟悉,写起系统来更加顺畅