如何使用反应路由器useHistory挂钩与TypeScript



在我的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]);
...
};

但它给出了一个错误:

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)

如何修复?

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

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

let history = useHistory();

react路由器文档对history.push函数有如下说明:

push(路径,[状态](-(函数(将新条目推送到历史堆栈

我不确定userHistory是什么类型的变量,但它需要是一个状态变量。我可以看出这不是因为你没有导入useState。使用useEffect导入useState,如下所示:

import React, { useEffect, useState } from 'react';

并像这样声明变量:

const [ userHistory, setUserHistory ] = useState();

然后您可以设置userHistory:

setUserHistory("foo");

来源:

React Router历史记录更新

ReactJS useState文档

相关内容

  • 没有找到相关文章

最新更新