如何在react js中移动列表中的项目



`嗨,伙计们,我需要react js的帮助,结果是我想把一个项目从一个特定的列表移到最后一个位置,但当我移动它时,它不会加载我以前的数据,不幸的是,我对react js和ps很陌生,我不是都知道吗,所以我求助于这个社区寻求帮助,很快我就会上传代码,希望你能帮助我,谢谢。

const [categories, setCategories] = useState<CategoriesWithSubsCategories>()
const listSelectCategory = categories?.list.map(cat => {
const { category, id } = cat.category
return {
value: id,
label: category
}
}).filter(cat => cat.label !== 'Otros')
listSelectCategory?.sort((a, b) => a.label.localeCompare(b.label)).push({ value: 'Otros', label: 'Otros' })``

正如您在上面看到的,尝试使用filter属性来过滤该类别,然后使用push属性将其添加到列表的末尾,它起作用了,但不是应该如何起作用,因为我想放在列表末尾的类别应该会给我带来一些子类别,但它没有,它确实起作用,这就是我的问题所在。">

尝试使用setState变量设置结果。我在任何地方都看不到。

如果您想访问名为categories的变量的数据,请在代码底部添加此行,它将使用setState函数更新变量的值。

setCategories(listSelectCategory)

您可以这样做:

const [categories, setCategories] = useState<CategoriesWithSubsCategories>();
...
// suppose categories is defined
setCategories((prev) => {
const newList = [...prev.list];
newList.push(newList.splice(newList.findIndex((item) => item.label === "Otros"),1)[0]);
return {
...prev,
list: newList
};
});

最新更新