網站搜尋

reactjs - React Typescript:屬性 'history' 在類型 'PropsInterface' 上不存在


我正在嘗試在資料庫呼叫失敗時使用 props.history.push('/'); 進行重定向,但我收到錯誤 Property 'history' does not exist on type 'PropsInterface'。更令人困惑的是,我已經從父組件傳入了 props,並且在 PropsInterface 中定義了它們。我要如何擴展這個介面以允許使用 history?

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

答案#1

在這裡 PropsInterface 無法訪問 history。所以要獲取 history,你需要使用由 withRoutes() 提供的 RouteComponentProps

像下面這樣修改你的程式碼:

interface PropsInterface extends RouteComponentProps<any> {}

希望這對你有幫助。