简体   繁体   English

RouteComponentProps 与 useHistory

[英]RouteComponentProps vs useHistory

Using React functional components and Typescript, would there be any difference between using the useHistory hook vs RouteComponentProps (react router v5.1)?使用 React 功能组件和 Typescript,使用 useHistory hook 与 RouteComponentProps (react router v5.1)会有什么区别吗?

Example using RouteComponentProps:使用 RouteComponentProps 的示例:

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

interface PropsType extends RouteComponentProps {
    text: string;
}

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

Example using useHistory:使用 useHistory 的示例:

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

interface PropsType {
    text: string;
}
const MyFunctionalComponent = ({
    text
  }: PropsType) => {
    const history = useHistory();
};

I am exactly in the same situation, and I want to share my conclusions with you.我的情况完全一样,我想和你分享我的结论。

First of all, the behavior of the programatic navigation with both approaches is the same, as they both use the same history instance , but there are some differences in the way of using them:首先,这两种方法的程序化导航的行为是相同的,因为它们都使用相同的history实例,但是使用它们的方式存在一些差异:

  • Using the member history of RouteComponentProps forces you to drill it all the way down your component tree using props.使用RouteComponentProps的成员history会强制您使用 props 一直向下钻取组件树。 There is nothing wrong with this approach, but if your component tree grows you may find yourself drilling through many layers of components.这种方法没有任何问题,但是如果您的组件树增长,您可能会发现自己钻透了许多层的组件。

  • Using useHistory hook you can avoid the previous prop drilling and just allow you to use the history instance in any functional component.使用useHistory钩子可以避免之前的 prop 钻取,只允许您在任何功能组件中使用history实例。 Note that this hook is a quick stopgap for a future hook and will be replaced eventually by a useNavigate hook.请注意,此钩子是未来钩子的快速权宜之计,最终将被useNavigate钩子取代。

Personally, I find the useHistory hook a cleaner and more readable solution for long component trees, but I keep using the history instance of RouteComponentProps if the component is close or a direct child of a Route component.就个人而言,我发现useHistory钩子对于长组件树来说是一种更清晰、更易读的解决方案,但是如果组件是关闭的或者是Route组件的直接子组件,我会继续使用RouteComponentPropshistory实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM