ajax.md 2.3 KB
Newer Older
A
afc163 已提交
1 2
# 动态加载数据

Z
zhujun24 已提交
3
- order: 4
A
afc163 已提交
4

5
远程读取的表格是**更为常见的模式**,下面的表格使用了 `dataSource` 对象和远程数据源绑定和适配,并具有筛选、排序等功能以及页面 loading 效果。
A
afc163 已提交
6

J
jljsj 已提交
7
**注意,此示例是静态数据模拟,数据并不准确,请打开网络面板查看请求。**
A
afc163 已提交
8

A
afc163 已提交
9 10 11
---

````jsx
A
afc163 已提交
12
var Table = antd.Table;
13
var Button = antd.Button;
A
afc163 已提交
14

A
afc163 已提交
15 16
var columns = [{
  title: '姓名',
17 18 19 20 21 22 23 24
  dataIndex: 'name',
  filters: [{
    text: '姓李的',
    value: ''
  }, {
    text: '姓胡的',
    value: ''
  }]
A
afc163 已提交
25 26
}, {
  title: '年龄',
27 28
  dataIndex: 'age',
  sorter: true
A
afc163 已提交
29 30 31 32 33
}, {
  title: '住址',
  dataIndex: 'address'
}];

A
afc163 已提交
34
var dataSource = new Table.DataSource({
35 36 37
  url: "/components/table/demo/data.json",
  resolve: function(result) {
    return result.data;
A
afc163 已提交
38
  },
39
  data: {},
A
afc163 已提交
40 41 42 43 44 45
  // 和后台接口返回的分页数据进行适配
  getPagination: function(result) {
    return {
      total: result.totalCount,
      pageSize: result.pageSize
    }
46
  },
A
afc163 已提交
47 48
  // 和后台接口接收的参数进行适配
  // 参数里提供了分页、筛选、排序的信息
A
afc163 已提交
49
  getParams: function(pagination, filters, sorter) {
A
afc163 已提交
50
    console.log('getParams 的参数是:', pagination, filters, sorter);
A
afc163 已提交
51 52 53
    var params = {
      pageSize: pagination.pageSize,
      currentPage: pagination.current,
A
afc163 已提交
54 55
      sortField: sorter.field,
      sortOrder: sorter.order
A
afc163 已提交
56
    };
Y
yiminghe 已提交
57
    for (var key in filters) {
A
afc163 已提交
58 59
      params[key] = filters[key];
    }
A
afc163 已提交
60
    console.log('请求参数:', params);
61
    return params;
62
  }
A
afc163 已提交
63 64
});

A
afc163 已提交
65
var Test = React.createClass({
A
afc163 已提交
66
  getInitialState() {
Y
yiminghe 已提交
67
    return {
A
afc163 已提交
68
      dataSource: dataSource
Y
yiminghe 已提交
69 70
    };
  },
A
afc163 已提交
71
  refresh() {
Y
yiminghe 已提交
72
    this.setState({
A
afc163 已提交
73 74 75 76 77 78 79 80 81 82 83
      dataSource: dataSource.clone()
    });
  },
  changeAndRefresh() {
    // 可以修改原来的 dataSource 再发请求
    this.setState({
      dataSource: dataSource.clone({
        data: {
          city: 'hz'
        }
      })
Y
yiminghe 已提交
84 85
    });
  },
A
afc163 已提交
86
  render() {
Y
yiminghe 已提交
87
    return <div>
A
afc163 已提交
88
      <Table columns={columns} dataSource={this.state.dataSource} />
89
      <Button type="primary" onClick={this.refresh}>
A
afc163 已提交
90
        重新加载数据
91
      </Button>
A
afc163 已提交
92
      &nbsp;
93
      <Button onClick={this.changeAndRefresh}>
A
afc163 已提交
94
        加载 city=hz 的数据
95
      </Button>
A
afc163 已提交
96
    </div>;
Y
yiminghe 已提交
97 98
  }
});
99

Y
yiminghe 已提交
100
React.render(<Test />, document.getElementById('components-table-demo-ajax'));
A
afc163 已提交
101
````