如何正确检查商店中是否存在action.payload



我正在尝试创建一个函数,如果action.payload不存在,则将其放入存储中,否则将其删除。

state.selected = []; //initial
action.payload = {...}

切片.ts:

userSelect(state, action: PayloadAction<IUser>) {
if (state.selected.length > 0) {
for (let i = 0; i < state.selected.length + 1; i++) {
if (state.selected[i].id === action.payload.id) {   //state.selected[i] -> Proxy; state.selected[i].id = undefined
state.selected.filter(e => e !== action.payload)
} else {
state.selected = state.selected || []
state.selected.push(action.payload)
}
}
} else {
state.selected = state.selected || []
state.selected.push(action.payload)
}
}

我正在尝试检查数组state.selected是否存在action.paylod的id,但我无法从state.selectd中获取id,因为它是代理类型,我用于检查单个例如state.selected[0]的日志返回为Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}

对于日志记录,您可以使用import { current } from '@reduxjs/toolkit'console.log(current(state))。此外,请注意,.filter不会更改您的数组,而是返回一个新的数组,因此您必须执行state.selected = state.selected.filter(e => e !== action.payload)

一般情况:

const foundIdx = state.selected.findIndex(selected => selected.id === action.payload.id)
if (foundIdx >= 0) {
state.selected.splice(foundIdx, 1)
} else {
state.selected.push(action.payload)
}

应该做所有你需要的

最新更新