损坏的创建切片选项类型@reduxjs/toolkit

f0brbegy  于 2023-01-09  发布在  其他
关注(0)|答案(4)|浏览(95)

在我的切片示例(redux/toolkit)中使用reducers时,我得到了这个错误。
'reducers' does not exist in type 'CreateSliceOptions<unknown, SliceCaseReducers<unknown>, string>'.ts(2345)
addPermissions以类型(CreateSliceOptions)存在,而不是以约简器存在。
我想我的 typescript 类型可能出了问题
代码:

import { createSlice } from "@reduxjs/toolkit";

interface IPermission {}

interface IState {
    userPermissions: IPermission[];
}

export const initialState: IState = {
    userPermissions: localStorage.getItem("token") ? [] : [],
};

export const permissionSlice = createSlice({
    name: "permissions",
    initialState,
    reducers: {
        addPermission: (state: any, action: any) => {
            state.userPermissions = action.payload;
        },
    },
});

export const { addPermission } = permissionSlice.actions;
export default permissionSlice.reducer;
py49o6xq

py49o6xq1#

我是还原版的维护者。

最有可能的 * 真实的 * 问题是在您的addPermissions减速器中使用(state: any, action: any) 不要这样做!**。

正确答案是 * 不 * 为state提供任何类型,因为它将从initialState字段自动推断,然后使用RTK的PayloadAction键入action参数:

export const permissionSlice = createSlice({
    name: "permissions",
    initialState,
    reducers: {
        addPermission: (state, action: PayloadAction<IPermission[]>) => {
            state.userPermissions = action.payload;
        },
    },
});

请确保您遵循Redux docs TS设置页面中显示的方法:

sq1bmfud

sq1bmfud2#

在您的代码中,切片状态的类型是IState,因此您应该将reducers字段的类型更新为SliceCaseReducers。

import { createSlice, SliceCaseReducers } from "@reduxjs/toolkit";

interface IPermission {}

interface IState {
    userPermissions: IPermission[];
}

export const initialState: IState = {
    userPermissions: localStorage.getItem("token") ? [] : [],
};

export const permissionSlice = createSlice({
    name: "permissions",
    initialState,
    reducers: {
        addPermission: (state: IState, action: any) => {
            state.userPermissions = action.payload;
        },
    } as SliceCaseReducers<IState>,
});

export const { addPermission } = permissionSlice.actions;
export default permissionSlice.reducer;
tcomlyy6

tcomlyy63#

尝试as以将类型视为SliceCaseReducers<IState>

reducers: {
    addPermission: (state: IState, action: any) => {
        state.userPermissions = action.payload;
    },
} as SliceCaseReducers<IState>,
1yjd4xko

1yjd4xko4#

这是由于redux node_modules损坏造成的。我删除了所有redux node_modules并重新安装,这修复了问题。

相关问题