reactjs - react typescript : Property 'history' does not exist on type 'PropsInterface'

标签 reactjs typescript react-router-v4

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

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> {}

希望这有帮助。

关于reactjs - react typescript : Property 'history' does not exist on type 'PropsInterface' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225023/

相关文章:

Angular 2用空值实例化类

reactjs - 警告 : You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored

reactjs - React Router BrowserRouter History Push & Google Analytics

javascript - 有没有办法在不使用 React 或 Vue 的情况下使用裁剪框在 JavaScript 中裁剪视频?

javascript - 无法通过 React Router 传递 props

javascript - Vue Typescript 组件库 - 使用 Webpack 和 SASS

typescript - NextJS VSCode Typescript ==> 断点未绑定(bind)

java - 创建 Docker 镜像之前构建前端

javascript - 如何在 Next Js (React) 中实现 adobe 分析?

javascript - 嵌套 react 路由器同级