React Ant Design踩坑记:Table用splice()删除行不生效

Ant Design 官方示例代码
https://ant.design/components/table/#components-table-demo-jsx
我简化一下:

import React from 'react';
import {
      Table, Space } from 'antd';

export default class a extends React.Component {
     
    constructor(props) {
     
        super(props);
        this.state = {
     
            dataSources: [{
      key: 1, id: 1 }, {
      key: 2, id: 2 }, {
      key: 3, id: 3 }]
        };
        this.columns = [
            {
     
                title: 'No',
                dataIndex: 'id'
            },
            {
     
                title: 'Action',
                key: 'action',
                render: (text, record) => (
                    <Space size="middle">
                        <a onClick={
     () => this.deleteRecord(record.id)} >Delete</a>
                    </Space>
                ),
            },
        ];
    }

    deleteRecord = (id) => {
     
    }

    render() {
     
        console.log(this.state.dataSources)
        return (
            <div>
                <Table columns={
     this.columns} dataSource={
     this.state.dataSources} >

                </Table>
            </div>
        )
    }
}

React Ant Design踩坑记:Table用splice()删除行不生效_第1张图片
问题是deleteRecord这个函数怎么写,思路是把点击delete的那行从数组里删掉,再重新setState
于是我用了JS里的splice()方法

  deleteRecord = (id) => {
     
        const newData = this.state.dataSources;
        console.log(this.state.dataSources);
        newData.splice(newData.findIndex(item => item._id === id), 1);
        this.setState({
     
            dataSources: newData
        })
        console.log(this.state.dataSources.length);
    }

看过去没毛病,运行用console.log输出的state也没毛病,点击Delete之后state里的数据确实被删掉了,那么到底为什么Table画面上没有被更新呢?
React Ant Design踩坑记:Table用splice()删除行不生效_第2张图片
查到最后发现其实是Ant Design现在的版本4.X版不支持splice()方法!我们改用filter()方法就好了!

    deleteRecord = (id) => {
     
        let newData = this.state.dataSources.filter(function (item) {
     
            return item.id !== id//返回你选中删除之外的所有数据
        })
        this.setState({
     
            dataSources: newData
        })
    }

重新保存,完美运行~ 如果你和我踩到了一样的坑,那快试试吧!

你可能感兴趣的:(react,javascript,reactjs,ant-design,demo)