React Typescript:属性'history'在类型 'PropsInterface' 上不存在



如果使用props.history.push('/');对数据库的调用失败,我正在尝试重定向,但我收到错误Property 'history' does not exist on type 'PropsInterface'进一步混淆事情我已经从父级传入了 props 并在PropsInterface中定义了它们 如何扩展此接口以允许历史记录

import React, { useContext, useEffect } from 'react';
import { RouteProps } from 'react-router';
import { RouteComponentProps } from 'react-router-dom';
import { Global } from '../globalState';
import { Dispatch, SET_SHARED } from '../globalState';

interface PropsInterface {
location: RouteProps['location'];
children: RouteProps['children'];
}
const Layout: React.FC<PropsInterface> = (props: PropsInterface) => {
const { global } = useContext(Global);
const { dispatch } = useContext(Dispatch);
useEffect(() => {
const callApi = async (path: string) => {
...
if (response.status === 200) {
localStorage.setItem('jwtToken', content.jwtToken);
dispatch({ type: SET_SHARED, value: content.shared });
} else {
localStorage.clear();
props.history.push('/');
//                ^
//                 Property 'history' does not exist on type 'PropsInterface'.ts(2339)
}
}
};

在这里PropsInterface无法访问历史记录。因此,要掌握历史记录,您需要使用随 withRoutes(( 提供的RouteComponentProps

修改代码,如下所示:

interface PropsInterface extends RouteComponentProps<any> {}

希望这有帮助。

最新更新