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

How to properly check action.payload for existence in the store?

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

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

Slice.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)
            }
        }

我正在尝试通过其 ID 检查数组 state.selected 是否存在 action.payload,但我无法从 state.selected 中获取 ID,因为它是代理类型,而我的日志检查单例state.selected[0] returns 作为 Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}

对于日志记录,您可以 import { current } from '@reduxjs/toolkit'console.log(current(state))。 另外,请注意 .filter 不会更改您的数组,而是 returns 一个新数组,因此您必须执行 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)
}

应有尽有