我试图使用UseState钩子从React中的对象数组中删除一个元素,但很难得到结果,因为接口不会重新渲染,对象也不会从中删除。
据我所知,要在react UI中反映对象的任何更新,我应该替换整个对象而不是更新它。我试图创建一个数组的副本,并通过函数内部的setDives方法分配它,但什么也没有。
下面是我的代码:
使用useState声明const。我只需要按名称删除特定的指南(本例中为“Lee”或“John”):
const [dives, setDives] = useState([
{ boat: 'Marcelo', divesite: '', guides: ['Lee', 'Jhon'] },
]);
删除功能:
function deleteGuide(i, guide) {
var tempArray = dives;
tempArray[dives.indexOf(i)].guides = dives[dives.indexOf(i)].guides.filter(
(e) => e !== guide,
);
setDives(tempArray);
}
界面按钮:
{dives.map((i) => (
<div>
{dives[dives.indexOf(i)].guides.map((guide) => (
<ButtonGroup>
<Button>{guide}</Button>
<Button onClick={() => deleteGuide(i, guide)}></Button>
</ButtonGroup>
))}
</div>
))}
3条答案
按热度按时间ozxc1zmp1#
你说得对,你必须创建一个新的数组副本,但你实际上没有这样做。这就是为什么它不工作。
更改此行:
setDives(tempArray);
为:setDives([...tempArray]);
说明:当只设置tempArray时,您只更新引用,它不会更改,因为
tempArray = dives
。由于没有更改,因此不会重新渲染,也不会看到任何结果。通过使用扩展操作符...
,构造了一个全新的Array,因此状态发生了变化(这会触发重新渲染)。进一步阅读:https://react.dev/learn/updating-arrays-in-state
为了更容易理解,你可以在setDives(tempArray)-语句之前添加一个console.log,然后看看输出:
e0bqpujr2#
有几样东西我会推荐。
1.为潜水和向导添加id到数据集(这意味着将向导从名称字符串更改为带有
id
和name
的对象。它有助于减轻当你在map
ping数组并试图添加键时React会给予你的一些警告。1.在button元素上使用这些id作为data attributes。您可以在按钮处理程序中选择它们,并使用它们来帮助您筛选数据集。
bprjcwpo3#
调用
setDives
时,应使用setState
的函数版本。您可以使用structuredClone
创建当前状态的深层副本。**注意:**在调用
map
时,还需要使用key
prop。