开发环境: 反应 + 打字稿 + 连接反应路由器
我的意图: 我想在用户操作中异步使用路由器操作。因此,当登录完成时,我希望我的应用程序进入主屏幕。
错误消息:“CallHistoryMethodAction<[string, unknown?]>”类型的参数不可分配给“UserActionType”类型的参数
错误代码:
export const login = (data: { id: string; password: string }) => async (
dispatch: Dispatch<UserActionType>,
): Promise<void> => {
await dispatch(loginRequest());
try {
const result = await apis.usersApi.login(data);
if (!result.data || !result.data.id) {
throw Error();
}
await dispatch(loginSuccess(result.data));
sessionStorage.setItem('mi', result.data.id);
await dispatch(actions.router.push('/')); <- ts error!
} catch (error) {
console.dir(error);
if (!error.response) {
await dispatch(loginFailure('서버 요청을 확인 해 주세요'));
}
if (error.response.status === 400) {
await dispatch(loginFailure('id 혹은 password를 확인 해 주세요'));
} else {
await dispatch(loginFailure('로그인 할 수 없습니다'));
}
}
};
用户操作类型代码:
import * as ActionTypes from '../rootActionTypes';
export interface IApiKey {
id?: number;
api_key?: string;
expire_date?: string | null;
}
export interface IUser {
id: number;
username: string;
email: string;
first_name: string;
last_name: string;
is_staff: boolean;
last_login: string;
date_joined: string;
api_keys?: Array<IApiKey>;
}
export interface IPolicyPWState {
id: number;
config_name: string;
config_data: string;
}
export interface IUserState {
user: IUser;
userLists: Array<IUser>;
userList: IUser;
isLoading: boolean;
addedUser: boolean;
deletedUser: boolean;
isRefreshAPI: boolean;
pwPolicy: Array<IPolicyPWState>;
error: string;
}
// login action type
interface loginRequestAction {
type: typeof ActionTypes.LOGIN_REQUEST;
}
interface loginSuccessAction {
type: typeof ActionTypes.LOGIN_SUCCESS;
data: IUser;
}
interface loginFailureAction {
type: typeof ActionTypes.LOGIN_FAILURE;
data: string;
}
...
export type UserActionType =
| loginRequestAction
| loginSuccessAction
| loginFailureAction
...
;
Root Reducer 代码:
import { connectRouter, RouterState } from 'connected-react-router';
import { History } from 'history';
import { combineReducers, Reducer } from 'redux';
import user from './users/reducers';
import board from './board/reducers';
import api from './api/reducers';
import { IUserState } from './users/users.types';
import { IBoardState } from './board/board.types';
export interface RootState {
user: IUserState;
router: RouterState;
board: IBoardState;
api: any;
}
const createRootReducer = (history: History): Reducer<RootState> =>
combineReducers({
router: connectRouter(history),
user,
board,
api,
});
export { createRootReducer };
问题:如何创建包含路由器操作的 Rootaction?
答案 0 :(得分:0)
我有同样的错误信息。我不知道它是否对你有帮助我也不想和我一起解决你的问题,因为我相信你的代码片段是不可执行的。
看这里:
dispatch: Dispatch<UserActionType>
您通过泛型指示您只有 UserActionType 类型的调度类型。但是你也有 Connected React Router 的 Type 。如果您删除 <UserActionType>
泛型