这种问题的原因可以是缺少 key 值,导致 React 不知道如何正确地重新渲染组件。所以,在重新渲染组件时,需要将一个唯一的 key 值作为组件的属性之一。
例如,使用 Antd 表格组件时,如果我们想要动态改变数据内容,可以在表格的 columns 中设置 key 值:
import { Table } from 'antd';
const dataSource = [ { key: '1', name: 'Mike', age: 32, address: '10 Downing Street' }, { key: '2', name: 'John', age: 42, address: '10 Downing Street' } ]
const columns = [ { title: 'Name', dataIndex: 'name', key: 'name' }, { title: 'Age', dataIndex: 'age', key: 'age' }, { title: 'Address', dataIndex: 'address', key: 'address' } ];
function App() { const [data, setData] = useState(dataSource);
const handleChangeData = () => { setData([ { key: '3', name: 'Bob', age: 26, address: '10 Downing Street' } ]); };
return (
在上面的代码示例中,每个数据项都有一个 key 值,这样在重新渲染表格时 React 就可以通过 key 值进行对比,正确渲染组件。
上一篇:Antd表格-排序与渲染不起作用
下一篇:Antd表格不显示第一行