javascript - 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 />
</>
);
}
本质上,我想通过单击最后一列中的删除图标来删除表行。但是,当我加载页面时,我收到“渲染的钩子比上一次渲染时更多”错误。我不知道如何解决它。有人能帮我吗?
解决方案
AntD 组件代码中抛出了该错误,但仅由于您指定表格道具的方式而出现。
问题出在您的ClassTheory
组件中,expandRowRender
您没有ClassTheoryDataTable
正确实例化子表。
const expandedRowRender = () => {
const table = new ClassTheoryDataTable();
return table;
};
这里你直接调用函数组件并返回它,但这不是 React 组件的实例化方式。在 React 中,您通过 JSX 描述 UI 并将其传递给 React,React 处理整个组件生命周期,从实例化、安装、重新渲染和卸载。
这个函数应该返回有效的 JSX。
const expandedRowRender = () => {
return <ClassTheoryDataTable />;
};
推荐阅读
- c++ - 如何创建一个函数来读取/写入数据到结构成员?
- javascript - 旋转图 8 - 以时间间隔将路径留在屏幕上
- android - “这种类型是最终的,所以它不能被继承” - ViewPager2
- c++ - 问题渲染到纹理 D3D11
- node.js - 带有实验模块的节点模块路径别名
- android - Kotlin:滑动刷新布局后分页Recyclerview不起作用
- javascript - 在 If == 语句中选择 2 件事?
- angular7 - 如何将令牌功能放在一个文件中并导入我需要的地方
- c# - 在 ASP.NET 页面中的用户控件之间切换的正确做法
- sql - 通过 GROUP BY 语句中的另一列的 MAXIMUM 和二进制变量选择另一条记录 - SQL Server