gpt4 book ai didi

typescript - 如何在 typescript 中设置 redux reducer 的初始状态?

转载 作者:行者123 更新时间:2023-12-05 07:07:39 25 4
gpt4 key购买 nike

我收到此 TypeScript 错误属性“hasError”在类型“(state: ErrorType | undefined, action: ErrorActionType) => ErrorType”上不存在。我认为它提示为 reducer 设置 initialState。

import { ErrorType, ErrorActionType } from '../actions';
import { ActionTypes } from '../types';

export const errorReducer = (
state: ErrorType = { hasError: false, errorMessage: '' },
action: ErrorActionType
) => {
switch (action.type) {
case ActionTypes.setError:
return action.payload;
default:
return state;
}
};

这是我的 Action

import { Dispatch } from 'redux';
import { ActionTypes } from '../types';

export interface ErrorType {
hasError: boolean;
errorMessage: string;
}
export interface ErrorActionType {
type: ActionTypes.setError;
payload: ErrorType;
}

export const setError = (hasError: boolean, errorMessage: string) => {
return (dispatch: Dispatch) => {
dispatch<ErrorActionType>({
type: ActionTypes.setError,
payload: { hasError, errorMessage },
});
};
};

还有我的 reducer.index

import { combineReducers } from 'redux';
import { errorReducer } from './error';
import { loadingReducer } from './loading';
import { newsReducer } from './news';
import { schoolsReducer } from './schools';

import { StoreStateType } from '../types';

export const reducers = combineReducers<StoreStateType>({
isLoading: loadingReducer,
hasError: errorReducer.hasError,
errorMessage: errorReducer.errorMessage,
news: newsReducer,
schools: schoolsReducer,
});

这是应用状态类型

export interface StoreStateType {
isLoading: boolean;
hasError: boolean;
errorMessage: string;
news: NewsType[];
schools: SchoolType[];
}

最佳答案

也许你可以尝试:hasError typeof false 作为参数。

这是我在将 typescript 与 reducer 和 useContext 一起使用时遇到的问题。

export const setError = (hasError typeof false, errorMessage: string) => {
return (dispatch: Dispatch) => {
...
};
};

关于typescript - 如何在 typescript 中设置 redux reducer 的初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com