我正在尝试将authenticationReducer添加到组合的reducer,但这给了我以下错误,
import { combineReducers } from "redux";
import { authenticationReducer } from "./authentication-reducer";
import { AuthResponse } from "../../services/authentication-service";
export interface StoreState {
authentication: AuthResponse;
}
export const rootReducer = combineReducers<StoreState>({
authentication: authenticationReducer
});
动作
import {
authenticationService,
AuthResponse
} from "../../services/authentication-service";
import { Dispatch } from "redux";
import { AuthActionTypes } from "./types";
export interface AuthenticationAction {
type: AuthActionTypes;
payload: AuthResponse | null;
}
export const authenticate = (credentials: any) => {
return async (dispatch: Dispatch) => {
dispatch<AuthenticationAction>({
type: AuthActionTypes.AUTHENTICATING,
payload: null
});
await authenticationService
.authenticate(credentials)
.then(response => {
if (response.data.access_token) {
console.log(response);
localStorage.setItem("authResponse", JSON.stringify(response));
dispatch<AuthenticationAction>({
type: AuthActionTypes.AUTHENTICATED,
payload: response.data
});
} else {
dispatch<AuthenticationAction>({
type: AuthActionTypes.AUTHENTICATION_FAILED,
payload: null
});
}
})
.catch((error: any) => {
dispatch({
type: AuthActionTypes.AUTHENTICATION_FAILED,
payload: error
});
});
};
};
减速器
import { AuthActionTypes } from "../actions/types";
import { AuthenticationAction } from "../actions/authentication-actions";
import { AuthResponse } from "../../services/authentication-service";
let authResponse = JSON.parse(localStorage.getItem("authResponse") || "{}");
const initialState = authResponse
? { loggedIn: true, authResponse: authResponse }
: {};
export const authenticationReducer = (
state: AuthResponse,
action: AuthenticationAction
) => {
switch (action.type) {
case AuthActionTypes.AUTHENTICATED:
return action.payload;
default:
return state;
}
};
存储配置
import { createStore, applyMiddleware, compose } from "redux";
import { rootReducer } from "./reducers";
import thunk from "redux-thunk";
export const configureStore = () => {
return createStore(rootReducer, applyMiddleware(thunk));
};
不确定在这里我在做什么错。任何帮助表示赞赏。谢谢。
答案 0 :(得分:0)
let尝试将default value
中的reducer
状态分配给initialState
。最初它可能为空/未定义,这就是为什么您收到错误消息“ undefined
无法分配给AuthResponse
”
export const authenticationReducer = (
state: AuthResponse = initialState, // assigning default value
action: AuthenticationAction
) => {
switch (action.type) {
case AuthActionTypes.AUTHENTICATED:
return action.payload;
default:
return state;
}
};
另一个技巧是,您可以将state
的类型更改为any
。但这不会检查您定义的类型。