【问题标题】:React typescript redux reducer type 'never'React typescript redux reducer 类型“从不”
【发布时间】:2022-07-31 18:06:47
【问题描述】:

我想使用 'useSelector' 选择正确的 rootStore 状态,但无法正确获取状态。原因是 RootState 的 auth reducer 永远不会给我类型。

如何正确访问用户对象中的任何值?

我的商店是这样的:

export const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export const persistor = persistStore(store);

export default { store, persistor};

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;

export type RootStore = ReturnType<typeof rootReducer>

export type AppDispatch = typeof store.dispatch;

我的 auth reducer 看起来像这样:

import {
  LOGIN_SUCCESS,
  LOGIN_FAIL,
  LOGIN_REQUEST,
  LoginDispatchTypes,
} from "../actions/types";
import { User } from "../types/index";

interface initialStateI {
  token: string;
  isAuthenticated: boolean;
  isLoading: boolean;
  user?: User;
  error: string;
}

const initialState = {
  token: "",
  isAuthenticated: false,
  isLoading: false,
  error: "",
};
export default function (
  state: initialStateI = initialState,
  action: LoginDispatchTypes
) {
  switch (action.type) {
    case LOGIN_REQUEST:
      return {
        ...state,
        isLoading: true,
      };
    case LOGIN_SUCCESS:
      return {
        ...state,
        isAuthenticated: true,
        isLoading: false,
        user: action.payload.user,
        token: action.payload.access_token,
        error: null,
      };
    case LOGIN_FAIL:
      return {
        ...state,
        isAuthenticated: false,
        token: null,
        user: null,
        error: action.payload.message,
      };

    default:
      return state;
  }
}

我的动作是这样的:

export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";
export const LOGIN_REQUEST = "LOGIN_REQUEST";
import { User } from "../types/index";

export interface LoginSuccess {
  type: typeof LOGIN_SUCCESS;
  payload: {
    expires_in: number;
    user: User;
    access_token: string;
    token_type: string;
  };
}

export interface LoginFail {
  type: typeof LOGIN_FAIL;
  payload: {
    message: string;
  };
}

export interface LoginRequest {
  type: typeof LOGIN_REQUEST;
}

export type LoginDispatchTypes = LoginRequest | LoginFail | LoginSuccess;

这就是我尝试在视图中显示用户详细信息的方式:

  const { user : currentUser} = useSelector((state:RootState) => state.auth);

用户类型也是这种格式:

export interface User {
  email: string;
  author_id: number;
}

任何有关如何从州访问数据的建议或建议/有用的链接都将受到高度赞赏。

【问题讨论】:

    标签: javascript reactjs typescript redux


    【解决方案1】:

    如果您不想添加任何其他类型,则应使用 redux-toolkit 中的 configureStore 而不是 createStore

    看来这是redux团队推荐的https://redux.js.org/usage/usage-with-typescript#define-root-state-and-dispatch-types

    【讨论】: