如何在 createSlice reducer prepare 函数中创建实体 ID

How to create entity IDs in the createSlice reducer prepare function

我在 redux-toolkit 的 createSlice 函数中包含的 addEntity reducer 中包含的 prepare 回调函数遇到了一些问题。

我正在尝试使用 prepare 回调将唯一 ID 添加到我的操作负载中。

redux-toolkit createSlice documentation 说:

If you need to customize the creation of the payload value of an action creator by means of a prepare callback, the value of the appropriate field of the reducers argument object should be an object instead of a function. This object must contain two properties: reducer and prepare. The value of the reducer field should be the case reducer function while the value of the prepare field should be the prepare callback function.

这是我正在使用的代码(使用 TypeScript 编写):

import { createSlice, createEntityAdapter } from '@reduxjs/toolkit';
import { MyEntityType } from '../../js/types/MyEntityType';
import { v4 as uuidv4 } from 'uuid';

const myEntityAdapter = createEntityAdapter<MyEntityType>();

const { reducer, actions } = createSlice({
    name: 'myEntity',
    initialState: myEntityAdapter.getInitialState(),
    reducers: {
        addEntity: {
            reducer: myEntityAdapter.addOne,
            prepare: (payload) => ({...payload, id: uuidv4()}),
        },
        removeEntity: myEntityAdapter.removeOne,
        updateEntity: myEntityAdapter.updateOne,
    }
});

当我编译我的应用程序并测试使用 addEntity 操作创建实体时,prepare 回调似乎没有执行任何操作。

这是我使用 Redux DevTools 发送的操作:

{
 type: 'myEntity/addEntity',
 payload: {myPayloadTrait: 100, id: 'test'} // Expected behavior: this id should be overwritten in the prepare callback
}

结果状态:

myEntity: {
    ids: {
        0:"test"
    },
    entities: {
        "test": {
            myPayloadTrait: 100
            id: "test"
        }
    }
}

为什么我的 prepare 回调在有效载荷传递给 reducer 之前不覆盖 "test" id?任何帮助或指导将不胜感激。

准备回调必须return一个看起来像{payload?, meta?, error?}的对象。您的代码目前正在 return 直接处理预期的负载。

改为:

addEntity: {
  reducer: myEntityAdapter.addOne,
  prepare: (payload) => ({
    payload: {
      ...payload,
      id: uuidv4()
    }
  }),
}