react 使用antd 的table組件,批量操作後還存留之前的打鉤項

官網提供一個方法代碼如下:

import { Table, Button } from 'antd';

const columns = [{
  title: '姓名',
  dataIndex: 'name',
}, {
  title: '年齡',
  dataIndex: 'age',
}, {
  title: '住址',
  dataIndex: 'address',
}];

const data = [];
for (let i = 0; i < 46; i++) {
  data.push({
    key: i,
    name: `李大嘴${i}`,
    age: 32,
    address: `西湖區湖底公園${i}號`
  });
}

const App = React.createClass({
  getInitialState() {
    return {
      selectedRowKeys: [],
      loading: false,
    };
  },
  start() {
    this.setState({ loading: true });
    // 模擬 ajax 請求,完成後清空
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  },
  onSelectChange(selectedRowKeys) {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  },
  render() {
    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <div>
        <div style={{ marginBottom: 16 }}>
           <Button type="primary" onClick={this.start}
             disabled={!hasSelected} loading={loading}>操作</Button>
           <span style={{ marginLeft: 8 }}>{hasSelected ? `選擇了 ${selectedRowKeys.length} 個對象` : ''}</span>
        </div>
        <Table rowSelection={rowSelection} columns={columns} dataSource={data} />
      </div>
    );
  }
});

ReactDOM.render(<App />, mountNode);

但是我的數據存儲在Store中,使用這個修改數據,所以修改了相關的代碼,但是我想複雜了

this.state = {
    selectedRows: [],
    list: []
};

const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys changed: ${selectedRowKeys}`);
                this.props.Store.selection.keys = selectedRowKeys;
                this.props.Store.selection.rows = selectedRows;
                this.setState({
                    selectedRowKeys: this.props.Store.selection.keys
                })
                console.log('selectedRowKeys'+selectedRowKeys+JSON.stringify(this.props.Store.selection));
            },
            onSelect: (record, selected, selectedRows) => {
                console.log(record, selected, selectedRows);
                console.log(JSON.stringify(this.props.Store.selection))
            },
            onSelectAll: (selected, selectedRows) => {
                console.log(selected, selectedRows);
                console.log(JSON.stringify(this.props.Store.selection))

            }
        }

render:

<Table
                    pagination={{
                        position: "top",
                        total: this.props.Store.tableTotal,
                        pageSize: this.props.Store.tableSize,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: ["15", "25", "35"],
                        onShowSizeChange: (current, pageSize) => {
                            console.log(current, pageSize);
                            this.props.Store.tableSize = pageSize;
                            this.props.Store.fetchTable(pageSize, pageSize * (current - 1));
                        },
                        onChange: (current, pageSize) => {
                            console.log(current, pageSize);
                            this.props.Store.tableSize = pageSize;
                            this.props.Store.fetchTable(pageSize, pageSize * (current - 1));
                        }
                    }}
                    rowKey={"id"}
                    columns={[
                        {
                            title: "用戶名",
                            dataIndex: "user",
                            key: "user",
                            fixed: "left",
                            width: 210
                        },
                        {
                            title: "歷史記錄",
                            dataIndex: "history",
                            key: "history",
                            width: 100,
                            align: "center",
                            fixed: "right",
                            render: (text, record) => (
                                <Button type="dashed" onClick={() => this.handleOperation.history(record)} size="small">
                                    <Icon type="folder" />
                                    查看
                </Button>
                            )
                        },
                        {
                            title: "詳細信息",
                            dataIndex: "auth",
                            key: "auth",
                            width: 100,
                            align: "center",
                            fixed: "right",
                            render: (text, record) => (
                                <Button type="dashed" onClick={() => this.handleOperation.update(record)} size="small">
                                    <Icon type="edit" />
                                    修改
                </Button>
                            )
                        }
                    ]}
                    loading={this.props.Store.tableLoading}
                    dataSource={this.props.Store.tableConverter}
                     rowSelection={rowSelection}
                    scroll={{ x: 1690 }}
                />

操作與列表在不同組件,所以將他存儲到Store中,利用this.props.Store.selection.keys進行操作,在此修改這個值
這是操作的成功後清空this.props.Store.selection.keys的值:

if (Http.protocol(data, "SUCCESS")) {
                message.info(data.head.message);
                console.log('選擇操作的成功數量' + JSON.stringify(this.props.Store.selection.keys))
                this.props.Store.selection.keys = [];
                this.props.Store.selection.rows = [];
                this.props.Store.fetchTable();//重新刷新列表
                alert('刷新列表後的數據' + JSON.stringify(this.props.Store.selection.keys))
              } else {
                message.warning(data.head.message);
              }

但是未果,修改後,頁面還是現實打鉤,但實際沒有值了

我一直以爲react只有setState了纔可以更新,但是不是的,當數據更新後,也會觸發onChange事件,會重新渲染
最後解決了:
把渲染的時候使用的rowSelection ,直接把值寫成Store的值,就可以了,具體的代碼如下:

onSelectChange = (selectedRowKeys, selectedRows) => {
        this.props.Store.selection.rows = selectedRows;
        this.props.Store.selection.keys = selectedRowKeys;
    };

render() {
    const rowSelection = {
      selectedRowKeys: this.props.Store.selection.keys,
      onChange: this.onSelectChange,
    };
    return (
      <div className="result-table">
        <Table
          pagination={{
            position: "top",
            total: this.props.Store.tableTotal,
            pageSize: this.props.Store.tableSize,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ["15", "25", "35"],
            onShowSizeChange: (current, pageSize) => {
              console.log(current, pageSize);
              this.props.Store.tableSize = pageSize;
              this.props.Store.fetchTable(pageSize, pageSize * (current - 1));
            },
            onChange: (current, pageSize) => {
              console.log(current, pageSize);
              this.props.Store.tableSize = pageSize;
              this.props.Store.fetchTable(pageSize, pageSize * (current - 1));
            }
          }}
          rowKey={"id"}
          columns={[
            {
              title: "用戶名",
              dataIndex: "user",
              key: "user",
              fixed: "left",
              width: 210
            },
            {
              title: "歷史記錄",
              dataIndex: "history",
              key: "history",
              width: 100,
              align: "center",
              fixed: "right",
              render: (text, record) => (
                <Button type="dashed" onClick={() => this.handleOperation.history(record)} size="small">
                  <Icon type="folder" />
                  查看
            </Button>
              )
            },
            {
              title: "詳細信息",
              dataIndex: "auth",
              key: "auth",
              width: 100,
              align: "center",
              fixed: "right",
              render: (text, record) => (
                <Button type="dashed" onClick={() => this.handleOperation.update(record)} size="small">
                  <Icon type="edit" />
                  修改
            </Button>
              )
            }
          ]}
          loading={this.props.Store.tableLoading}
          dataSource={this.props.Store.tableConverter}
          rowSelection={rowSelection}
          scroll={{ x: 1690 }}
        />

      </div>
    );
  }

可以滿足需求了,奈斯,謝謝幫助我的小夥伴!

如果以上解決不了你的問題,可以參考以下地址。

參考的地址:
官網:http://lucifier129.github.io/ant-design/components/table/#demo-row-selection-and-operation

https://www.cnblogs.com/hujunzheng/p/5689650.html

https://www.jianshu.com/p/733ce55740db

https://www.jb51.net/article/147331.htm

https://blog.csdn.net/Mr_yangzc/article/details/85006029

https://blog.csdn.net/hbkc5/article/details/70919985
https://github.com/ant-design/ant-design/issues/3547

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章