Reactjs 如何将react router useHistory钩子与TypeScript一起使用

Reactjs 如何将react router useHistory钩子与TypeScript一起使用,reactjs,react-router,react-hooks,Reactjs,React Router,React Hooks,在我的func组件中,我尝试使用历史记录。按以下方式推送: import React, { useEffect } from 'react'; import { useHistory } from 'react-router-dom'; interface Props { question: Question; selectedAnswer: SelectedOption | undefined; } const LastScreen: React.FC<Props> =

在我的func组件中,我尝试使用
历史记录。按以下方式推送

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]);
  ...
};
import React,{useffect}来自“React”;
从'react router dom'导入{useHistory};
界面道具{
问题:问题;;
selectedAnswer:SelectedOption |未定义;
}
const LastScreen:React.FC=(道具:道具)=>{
const history=useHistory();
...
useffect(()=>{
如果(进度===100){
常量id=uuid();
历史推送({
路径名:`/p/${id}`,
状态:{userAnswers},
});
}
},[进度、用户答案、历史];
...
};
但它给出了一个错误:

类型为“{pathname:string;state:{userAnswers:userAnswers | undefined;};}”的参数不能分配给类型为“to”的参数。对象文字只能指定已知的属性,并且“state”在类型“PartialPath”中不存在。ts(2345)


如何修复它?

根据React Router文档(此处-,
历史记录)。push将单个路径字符串作为参数,而不是对象

比如说-
history.push('/home')

在尝试修复它之后,我发现在使用自定义历史记录时出现了问题,比如从“历史记录”导入历史记录
然后是
..
所以当我用
..
替换它时,问题就消失了。它可以选择将参数作为字符串,如
'/about'
或对象,如
{pathname:'/about',state:{…放置您想要传递的内容}