Redux 工具包 + Typescript:extraReducers

问题描述 投票:0回答:2

我正在尝试将打字稿添加到我的react/redux项目中。 这是我的切片:

import { createSlice, createAsyncThunk, AnyAction, CaseReducer, PayloadAction } from '@reduxjs/toolkit';
export interface RequestStateBase {
    failed: boolean;
    executing: boolean;
    initialLoad: boolean;
    message: string | null;
    errors: any[]
}
const handlePending = (state: RequestStateBase) => {
    state.failed = false;
    state.executing = true;
    state.message = '';
}

const createCharacter = createAsyncThunk(
    'character/new',
    async (model: any) => characterClient.createCharacter(model)
);

const characterSlice = createSlice({
    name: "character",
    initialState: initialState,
    reducers: {
        cleanCharacterData: (state: CharacterState) => {
            //...
        },
        //...
    },
    extraReducers: builder => {
        builder.addCase(createCharacter.pending, handlePending),
        //...
    }
});

在 VS Code 中一切正常,但在构建过程中出现以下错误:

Line 78:9:  Expected an assignment or function call and instead saw an expression  @typescript-eslint/no-unused-expressions

第78行指的是

builder.addCase(createCharacter.pending, handlePending)

如何解决这个问题?

typescript redux redux-toolkit
2个回答
6
投票

删除该行后面的

,
- 您可能想写
;

逗号运算符不会在那里造成任何真正的伤害,但通常会导致意外的行为 - 而且它似乎确实会激怒那里的 JSHint。


5
投票

对于任何在此处结束的谷歌搜索,我需要向

builder
参数添加类型注释,以便获得切片状态的类型推断。如果没有它,当我添加
extraReducers
时,切片就会推断为
any
类型。

例如,在我的

const authSlice = createSlice({ ... })
中,
extraReducers
字段现在输入为:
extraReducers: (builder: ActionReducerMapBuilder<AuthState>) => { ... }

© www.soinside.com 2019 - 2024. All rights reserved.