typescript - 动作函数不可调用 - 使用 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)
解决方案
得到它的工作。我有一些错误,但我认为最大的问题是尝试用 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;
推荐阅读
- vb.net - 如何获取每行 datagridview 的数据并将其显示在 ANOTHER FORM 的文本框中?VB.Net
- unix - 用于在特定列的管道分隔文件中查找和删除不需要的字符串的 unix shell 脚本
- php - Codeigniter 选择和统计 MySQL 记录
- hyperledger-fabric - 在 Kafka/Zookeeper 场景中,排序节点是否相互通信?
- java - load data from csv to mysql database using java
- r - I want to draw scatterplot in year and month
- java - PostgreSQL:列“BOOLEAN_VALUE”是数字类型,但表达式是布尔类型提示:您需要重写或强制转换表达式
- spring - How can I exclude the conditions evaluation report from the console of a Spring boot application?
- javascript - Knockout JS - 根据可观察字段设置表格宽度
- django - Django rest framework browsable api is rendering both a PUT and a POST form when it should only be rendering a POST form