如何通过 TypeScript 使用反应路由器 useHistory 钩子

Ale*_*ylo 7 reactjs react-router react-hooks

在我的 func 组件中,我尝试history.push以这种方式使用:

import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

interface Props {
  question: Question;
  selectedAnswer: SelectedOption | undefined;
}

const LastScreen: React.FC<Props> = (props: Props) => {
  const history = useHistory();
  ...
  
  useEffect(() => {
    if (progress === 100) {
      const id = uuid();
      history.push({
        pathname: `/p/${id}`,
        state: { userAnswers },
      });
    }
  }, [progress, userAnswers, history]);
  ...
};
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误:

Argument of type '{ pathname: string; state: { userAnswers: UserAnswers | undefined; }; }' is not assignable to parameter of type 'To'. Object literal may only specify known properties, and 'state' does not exist in type 'PartialPath'.ts(2345)

如何修复它?

小智 0

useHistory挂钩使您可以访问可用于导航的历史记录实例。

import { useHistory } from "react-router-dom";
  

let history = useHistory();
Run Code Online (Sandbox Code Playgroud)