首页 > 解决方案 > 动作函数不可调用 - 使用 Typescript、react-redux 和 redux-starter-kit

问题描述

使用 createSlice() 方法创建操作时出现 Typescript 错误“此表达式不可调用”。不应该toggleDarkTheme()返回调度时可以使用的动作吗?

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

import { AppState } from "../types";

const initialState: AppState = {
  darkTheme: false
};

const appStateSlice: Slice<AppState> = createSlice({
  name: "appState",
  initialState,
  reducers: {
    toggleDarkTheme: (state: AppState) => ({
      ...state,
      darkTheme: !state.darkTheme
    })
  }
});

export const { toggleDarkTheme } = appStateSlice.actions;
console.log(toggleDarkTheme()); //ERROR "expression is not callable"

export default appStateSlice.reducer;

这是完整的 TS 错误:

This expression is not callable.
  Not all constituents of type 'void | WithTypeProperty<WithMatch<() => WithPayload<undefined, Action<string>>, string, undefined, never, never>, string> | WithTypeProperty<WithMatch<{ (payload?: undefined): WithPayload<undefined, Action<...>>; <PT extends unknown>(payload?: PT | undefined): WithPayload<...>; }, string, unknown, never, never>, str...' are callable.
    Type 'void' has no call signatures.ts(2349)

标签: typescriptreduxreact-redux

解决方案


得到它的工作。我有一些错误,但我认为最大的问题是尝试用 Slice 输入它。我对 Typescript 很陌生,所以如果有人知道如何正确输入这个,我很想看看如何。

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

import { AppState } from "types";

const initialState: AppState = {
  darkTheme: false
};

const appStateSlice = createSlice({
  name: "appState",
  initialState,
  reducers: {
    toggleDarkTheme(state: AppState) {
      state.darkTheme = !state.darkTheme;
    }
  }
});

export const { toggleDarkTheme } = appStateSlice.actions;
console.log(toggleDarkTheme());

export default appStateSlice.reducer;

推荐阅读