如何从Redux状态的ReactJS数组中删除一个元素,当条件为真?



基本上,我有一个包含项目行的表。这些行有4个单元格,其中有文本。您可以从右侧的行中删除单元格/文本->离开了。所以"1 2 3 4;可以是1 2 3 - 1;例如,如果从右侧删除单元格/文本->离开。

这是我的减速器代码,我将不得不删除整个行,作为"1"在上面的例子中也被删除了。我只是不想让一行显示"- - - -"例如,它可以在这一点之前删除整行。下面是我的代码:

case DELETE_SITE: {
return {
...state,
siteRows: state.siteRows.map((s) => {
if (s.siteLevel2Id && s.siteLevel2Id == action.payload.id) 
//return {...s, siteLevel2Id: null, siteLevel2Name: null, canDeleteLevel2: null};
return state.siteRows.slice(0, 1);
if (s.siteLevel3Id && s.siteLevel3Id == action.payload.id) 
return {...s, siteLevel3Id: null, siteLevel3Name: null, canDeleteLevel3: null};
if (s.siteLevel4Id && s.siteLevel4Id == action.payload.id) 
return {...s, siteLevel4Id: null, siteLevel4Name: null, canDeleteLevel4: null};
if (s.siteLevel5Id && s.siteLevel5Id == action.payload.id) 
return {...s, siteLevel5Id: null, siteLevel5Name: null, canDeleteLevel5: null};
return s;
}),
}
}  

可以看到,只要删除3,2,1仍然会被填充,看起来像&;1 - - -&;。现在如果我们删除& 1"同样,这里命名为"siteLevel2…",它会显示"- - - -"但是我只想从"state.siteRows"中删除整行。

我已经尝试了现在正在注释的行,但它只是添加了一个"null"值转换为数组"siteRows",就像这样:{null, [siteRow1]}所以它在我的屏幕上崩溃了因为它试图做"null。id"。

我试过在第二行上拼接数组中的第一个元素(删除它),但它似乎也不起作用。

有谁能帮我一下吗?

您可以尝试以下操作:

const DELETE_SITE = 'DELETE_SITE';
const testReducer = (state, action) => {
switch (action.type) {
case DELETE_SITE: {
const keys = [
['siteLevel2Id', 2],
['siteLevel3Id', 3],
['siteLevel4Id', 4],
['siteLevel5Id', 5],
];
const reset = (num, item) => ({
...item,
[`siteLevel${num}Id`]: null,
[`siteLevel${num}Name`]: null,
[`canDeleteLevel${num}`]: null,
});
const recurCheck = (id) => (row) => {
const recur = (index) => {
const [currentKey, num] = keys[index];
//nothing to do, no match
if (index >= keys.length - 1) {
return row;
}
//row siteLevelNId matches id, reset this row
if (row[currentKey] && row[currentKey] == id) {
return reset(num, row);
}
//recur try the next index
return recur(index + 1);
};
return recur(0);
};
return {
...state,
siteRows: state.siteRows
.map(recurCheck(action.payload?.id))
//if any of these keys return true
//  do not remove this row
.filter((row) => keys.some(([key]) => row[key])),
};
}
default: {
return state;
}
}
};
console.log(
'no rows',
testReducer(
{ siteRows: [] },
{ type: DELETE_SITE, payload: { id: 1 } }
).siteRows
);
const createItem = (num) => ({
[`siteLevel${num}Id`]: num,
[`siteLevel${num}Name`]: num,
[`canDeleteLevel${num}`]: num,
});
console.log(
'id 3',
testReducer(
{ siteRows: [createItem(3)] },
{ type: DELETE_SITE, payload: { id: 3 } }
).siteRows
);
console.log(
'id 2',
testReducer(
{ siteRows: [{ ...createItem(2), siteLevel3Id: 3 }] },
{ type: DELETE_SITE, payload: { id: 2 } }
).siteRows
);

我试图清理重复的逻辑,但你可以让它保持原样,解决你的问题的是映射函数之后的过滤器函数。

最新更新