首页 > 解决方案 > 无法在组合减速器中减速器

问题描述

我正在尝试将 authenticationReducer 添加到组合减速器,但它给了我以下错误,

在此处输入图像描述

在此处输入图像描述 索引.ts,

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));
};

不知道我在这里做错了什么。任何帮助表示赞赏。谢谢。

标签: reactjsreact-redux

解决方案


让我们尝试将default value状态分配reducerinitialState。最初它可能为空/未定义,这就是您收到错误“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. 但这不会检查您定义的类型。


推荐阅读