我尝试为我的应用程序实现一个redux存储。
下面是我的app.ts
(主存储文件):
import { combineReducers, compose, createStore, Reducer } from 'redux';
import * as fromBarcode from './reducers/barcode';
export interface AppState {
barcode: fromBarcode.State;
}
const composeEnhancers: typeof compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer: Reducer<AppState> = combineReducers({
barcode: fromBarcode.reducer,
});
export const store = createStore(rootReducer, composeEnhancers());
这是./reducers/barcode
文件:
import * as actions from '../actions/barcode';
export interface State {
token: string | null;
}
const initialState: State = {
token: null,
};
export const reducer = (state: State = initialState, action: actions.BarcodeTypes): State => {
switch (action.type) {
case actions.SET_TOKEN:
return { ...state, token: action.payload.token };
default:
return state;
}
};
这是../actions/barcode
文件:
export const SET_TOKEN = '[Barcode] Set token';
// --- Interface --- //
export interface SetToken {
type: typeof SET_TOKEN;
payload: { token: string | null };
}
// --- Action creators --- //
export const setToken = (token: string | null): SetToken => {
return {
type: SET_TOKEN,
payload: { token },
};
};
export type BarcodeTypes = SetToken;
但是,由于某些原因,我不知道也不能理解我从app.ts
文件中得到以下错误:
Type 'Reducer<CombinedState<{ barcode: State; }>, SetToken>' is not assignable to type 'Reducer<AppState, AnyAction>'.
Types of parameters 'action' and 'action' are incompatible.
Type 'AnyAction' is not assignable to type 'SetToken'
有什么帮助吗?
此外,我还观察到,一旦我在reducer文件中将以下行(第11行)更改为export const reducer = (state: State = initialState, action: any): State => {
:export const reducer = (state: State = initialState, action: actions.BarcodeTypes): State => {
错误将消失
发布于 2021-07-01 14:20:45
解决这个问题的一种可能方法是为所有应用程序操作引入一个联合类型:
// union of all actions accepted by the barcode reducer, here just SetToken
type BarcodeAction =
| SetToken;
// union of all actions in the app, exported from different slices
type AppAction =
| BarcodeAction;
然后输入您的根缩减程序,并提供AppAction
类型作为第二个类型参数:
const rootReducer: Reducer<AppState, AppAction> = combineReducers({
barcode: barcode.reducer,
});
https://stackoverflow.com/questions/68211027
复制