如何在TypeScript中使用react-router useHistory挂钩

时间:2020-07-08 10:00:11

标签: 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]);
  ...
};

但出现错误:

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)

如何解决?

1 个答案:

答案 0 :(得分:0)

根据React Router文档(此处-https://reactrouter.com/web/api/Hooks/usehistory),history.push采用单个路径字符串作为参数,而不是对象。

例如- history.push('/ home');