组件只能访问数组的旧状态

问题描述 投票:0回答:1

我正在使用 React,我有一个用户可以从中添加和删除行的表。该表由一系列组件组成。每个组件/行都有一个垃圾桶图标,单击该图标时将执行删除行功能。似乎每个组件只能访问数组/表的旧状态,因此删除无法正常工作。有什么想法可以解决这个问题吗?

构成此表的

useState
数组中的组件示例:

<Row
  className={className}
  columns={columns}
  text={text}
  key={key}
  keyProp={key}
  deleteFunction={() => removeRow(key)}
/>

删除函数是数组中每一行/组件的道具:

function removeRow(key) {
  setMeals(meals.filter(i => i.props.keyProp !== key));
  // This should only remove the one row which had its trash can icon clicked.
  // If there's 10 rows and you click the trash can for row 4, rows 4-10
  // will be deleted.
  // If you click the trash can for row 7, rows 7-10 will be deleted and so on.
}
javascript reactjs react-state
1个回答
0
投票

尝试一下,我相信它会解决问题。

function removeRow(key) {
// This updates the previous meal array whenever there's a removal in the meal array
setMeals((prevMeals) => {
    return prevMeals.filter((meal) => meal.key !== key)
})

另外,改进您的删除功能,如下所示:

<Row className={className} columns={columns} text={text} key={key} keyProp={key} deleteFunction={() => removeRow.bind(null, key)} />
© www.soinside.com 2019 - 2024. All rights reserved.