使用immer将Redux状态数组替换为其他数组



我正在使用immer来管理我的redux状态。它有一个项目,它是一系列的客户。我的网站上有一个删除按钮,在删除按钮上,我想从我所在州的客户列表中的阵列中删除该项目。在这个例子中,我想删除Id 100

Redux状态

customers : [{Id: "100", Name: "John"},{Id: "200", Name: "Mark"}],
address: null,
randomStuff [{}]

代码

customerIdToBeDeleted = 100
const newCustomers = produce(customers, (draft) => {
const newCustomers = draft.filter((x) => x.Id !== customerIdToBeDeleted );
draft = newCustomers ;
}); 

这不起作用。它说不能重新分配参数草案。如何从数组中删除一个Id并将其存储在状态中?

在普通的reducer中,您将从旧数组返回一个新数组,这就是您在这里所做的。但Immer是以突变为基础的。您要做的不是重新分配,而是更改数组变量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);
})

编辑:我相信返回新值也是可以的。你就是不能把它分配给draft

const newCustomers = produce(customers, (draft) => {
return draft.filter(x => x.Id !== customerIdToBeDeleted );
}); 

最新更新