首页 > 解决方案 > React 错误:“渲染的钩子比上一次渲染时更多”

问题描述

我有以下组件。我在我的组件中使用了反应钩子(useHistory,useState)。

export default function ClassTheoryDataTable() {

const dataSource = [
    {
        key: '1',
        date: '18.03.2021',
        subject: 'Revision',
        inst: 'HASHEL',
        edit: 'edit',
        delete: 'delete'
    }
];

    let history = useHistory();
    const [tableData, setTableData] = useState(dataSource);

    const handleRedirect = (data) => {
        history.push("/ClassTheoryDetails");
    };

    const handleDelete = (key) => {
        let dataSource1 = [...tableData];
        dataSource1 = dataSource1.filter((item) => item.key !== key);
        setTableData(dataSource1);
    }

    const columns = [
        {
            title: 'Date',
            dataIndex: 'date',
            key: 'date',
            render: (text, record) => (
                <a onClick={() => handleRedirect(record)} type="text">{text}</a>
            )
        },
        {
            title: 'Subject',
            dataIndex: 'subject',
            key: 'subject',
            editable: true
        },
        {
            title: 'Inst.',
            dataIndex: 'inst',
            key: 'inst',
            editable: true
        },
        {
            title: '',
            dataIndex: 'edit',
            key: 'edit',
            width: '50px',
            render: (text, record) => (
                <Space size="middle">
                    <EditOutlined style={{ color: '#1589FF', fontSize: '15px' }} />
                </Space>
            )
        },
        {
            title: '',
            dataIndex: 'delete',
            key: 'delete',
            width: '50px',
            render: (text, record) => (
                dataSource.length >= 1 ?
                    <Popconfirm title="Sure to delete ?" onConfirm={() => handleDelete(record.key)}>
                        <CloseCircleFilled style={{ color: 'red', fontSize: '15px' }} />
                    </Popconfirm>
                    : null
            )
        }
    ];
    return (
        <>
            <Table columns={columns} dataSource={tableData} pagination={false} bordered />
        </>
    );
}

本质上,我想通过单击最后一列中的删除图标来删除表行。但是,当我加载页面时,我收到“渲染的钩子比上一次渲染时更多”错误。我不知道如何解决它。有人能帮我吗?

标签: javascriptreactjs

解决方案


AntD 组件代码中抛出了该错误,但仅由于您指定表格道具的方式而出现。

问题出在您的ClassTheory组件中,expandRowRender您没有ClassTheoryDataTable正确实例化子表。

const expandedRowRender = () => {
  const table = new ClassTheoryDataTable();
  return table;
};

这里你直接调用函数组件并返回它,但这不是 React 组件的实例化方式。在 React 中,您通过 JSX 描述 UI 并将其传递给 React,React 处理整个组件生命周期,从实例化、安装、重新渲染和卸载。

这个函数应该返回有效的 JSX。

const expandedRowRender = () => {
  return <ClassTheoryDataTable />;
};

推荐阅读