Reactjs 使用immer将Redux状态数组替换/更改为其他数组
我正在使用immer管理我的redux状态。它有一个项目,它是一个客户阵列。在我的网站上有一个删除按钮,在删除按钮上,我想从我所在州的客户列表中的数组中删除该项目。 在本例中,我想删除Id 100 雷多克斯州Reactjs 使用immer将Redux状态数组替换/更改为其他数组,reactjs,redux,react-redux,immer.js,Reactjs,Redux,React Redux,Immer.js,我正在使用immer管理我的redux状态。它有一个项目,它是一个客户阵列。在我的网站上有一个删除按钮,在删除按钮上,我想从我所在州的客户列表中的数组中删除该项目。 在本例中,我想删除Id 100 雷多克斯州 customers : [{Id: "100", Name: "John"},{Id: "200", Name: "Mark"}], address: null, randomStuff [{}] 代码 这
customers : [{Id: "100", Name: "John"},{Id: "200", Name: "Mark"}],
address: null,
randomStuff [{}]
代码
这是行不通的。它表示无法重新分配参数草稿。如何从数组中删除一个Id并将其存储在状态中?在普通的reducer中,您将从旧数组返回一个新数组,这就是您在这里所做的。但伊默是以变异为基础的。您要做的不是重新分配,而是更改数组变量
draft
的内容。我们通过调用诸如push()
,pop()
,以及在本例中的splice()
等变异方法来实现这一点
Immer文档中有一个示例适用于此
// delete by id
const deletedTodosArray = produce(todosArray, draft => {
const index = draft.findIndex(todo => todo.id === "id1")
if (index !== -1) draft.splice(index, 1)
})
就你而言,它是:
const customerIdToBeDeleted = "100"; // since your customer ids are strings
const newCustomers = produce(customers, (draft) => {
const index = draft.findIndex(x => x.Id === customerIdToBeDeleted);
if (index !== -1) draft.splice(index, 1);
})
编辑:
我相信返回新值也是可以的。您无法将其分配给草稿
const newCustomers = produce(customers, (draft) => {
return draft.filter(x => x.Id !== customerIdToBeDeleted );
});
const newCustomers = produce(customers, (draft) => {
return draft.filter(x => x.Id !== customerIdToBeDeleted );
});