## 改造列表页 1. 基于dva数据流改造需要做如下修改 * 增加connect ~~~ @connect(({ demo, loading }) => ({ demo, loading: loading.models.demo, })) @Form.create() class Demo extends PureComponent { } ~~~ * 修改handelSearch方法,使用dispatch调用数据流 ~~~ handleSearch = params => { const { dispatch } = this.props; dispatch({ type: 'demo/fetchList', payload: params, }); }; ~~~ * 删除Demo中的state的data字段并且将render方法内从state获取date的代码替换为从props获取,其中的demo则是从connect连接到model内的namespace名,demo.data则对应model内state的data字段。 ~~~ state = { selectedRows: [], }; ~~~ ~~~ render() { const code = 'demo'; const { form, loading, demo: { data }, } = this.props; ............... } ~~~ 2. 完整代码如下 ~~~ import React, { PureComponent } from 'react'; import { Button, Col, Form, Input, message, Row } from 'antd'; import { connect } from 'dva'; import Grid from '../../../components/Sword/Grid'; import Panel from '../../../components/Panel'; const FormItem = Form.Item; @connect(({ demo, loading }) => ({ demo, loading: loading.models.demo, })) @Form.create() class Demo extends PureComponent { state = { selectedRows: [], }; onSelectRow = rows => { this.setState({ selectedRows: rows, }); }; getSelectKeys = () => { const { selectedRows } = this.state; return selectedRows.map(row => row.id); }; // ============ 查询 =============== handleSearch = params => { const { dispatch } = this.props; dispatch({ type: 'demo/fetchList', payload: params, }); }; // ============ 查询表单 =============== renderSearchForm = onReset => { const { form } = this.props; const { getFieldDecorator } = form; return ( <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={6} sm={24}> <FormItem label="标题"> {getFieldDecorator('title')(<Input placeholder="请输入标题" />)} </FormItem> </Col> <Col> <div style={{ float: 'right' }}> <Button type="primary" htmlType="submit"> 查询 </Button> <Button style={{ marginLeft: 8 }} onClick={onReset}> 重置 </Button> </div> </Col> </Row> ); }; test = () => { const keys = this.getSelectKeys(); if (keys.length === 0) { message.warn('请先选择一条数据!'); } else { console.log(`已选择数据id:${keys}`); } }; renderLeftButton = () => ( <Button icon="tool" onClick={this.test}> 测试 </Button> ); render() { const code = 'demo'; const { form, loading, demo: { data }, } = this.props; const columns = [ { title: '标题', dataIndex: 'title', }, { title: '内容', dataIndex: 'content', }, { title: '时间', dataIndex: 'date', }, ]; return ( <Panel> <Grid code={code} form={form} onSearch={this.handleSearch} onSelectRow={this.onSelectRow} renderSearchForm={this.renderSearchForm} renderLeftButton={this.renderLeftButton} loading={loading} data={data} columns={columns} /> </Panel> ); } } export default Demo; ~~~ 3. 打开系统,查看查询之后调用的接口及传递参数都正确。 ![](https://box.kancloud.cn/a458fc3fd335f09e202072e4d949d7b5_3254x1784.png) 4. 如此一来就已经将api调用、数据处理彻底解耦到了model 中。Demo页面只需关注UI与数据的绑定。