RouteComponentProps 与 useHistory

问题描述 投票:0回答:2

使用React功能组件和Typescript,使用useHistory hook与RouteComponentProps(react router v5.1)有什么区别吗?

使用 RouteComponentProps 的示例:

import { RouteComponentProps } from 'react-router-dom';

interface PropsType extends RouteComponentProps {
    text: string;
}

const MyFunctionalComponent = ({
    text,
    history
    }: PropsType) => {
  
};

使用 useHistory 的示例:

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

interface PropsType {
    text: string;
}
const MyFunctionalComponent = ({
    text
  }: PropsType) => {
    const history = useHistory();
};
reactjs typescript react-router
2个回答
2
投票

我的情况一模一样,想和大家分享一下我的结论。

首先,两种方法的程序化导航的行为是相同的,因为它们都使用相同的

history
实例,但是使用它们的方式有一些差异:

  • 使用

    history
    的成员
    RouteComponentProps
    会强制您使用 props 将其一直钻到组件树中。这种方法没有任何问题,但如果你的组件树不断增长,你可能会发现自己钻了很多层组件。

  • 使用

    useHistory
    钩子可以避免之前的 prop 钻孔,只允许您在任何功能组件中使用
    history
    实例。请注意,此钩子是未来钩子的快速权宜之计,最终将被
    useNavigate
    钩子取代。

就我个人而言,我发现

useHistory
钩子对于长组件树来说是一个更干净、更易读的解决方案,但如果组件是关闭的或者是
history
组件的直接子组件,我会继续使用
RouteComponentProps
Route
实例。


0
投票

对于那些遇到 useHistory 问题的人,它已在 React-router-dom v6 中被替换,现在你应该使用 useNavigate()。

示例:

import { useNavigate } from 'react-router-dom';

const navigate = useNavigate();

navigate('/404');

您不再需要“推”。

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.