简体   繁体   中英

react-router-dom v6 upgrade

We're going through the process of updating various NPM packages and currently looking at react-router-dom v5 -> v6. The documentation is pretty good, but I cant see how to account for some changes in the Route component.

In v5 we had the following:

<Switch>
  <Route
    path={`/reviewer/${reviewsMenuPath}/history/:acronym`}
    render={({ match }) => {
      const breadcrumbs = [
        { text: 'Reviews' },
        { text: 'History', link: `/reviewer/${reviewsMenuPath}/history` },
        { key: match.params.acronym }];
      return (
        <>
          <ComponentOne title="Your completed reviews" />
          <ComponentTwo
            acronym={match.params.acronym}
            key={match.params.acronym}
            breadcrumbs={breadcrumbs}
          />
        </>
      );
    }}
  />

but 'render' is no longer available in v6. I understand the requirement for Switch -> Routes and that I'll need to introduce element={} , but am unsure how to construct the breadcrumbs data so that its available for ComponentTwo ...would appreciate any suggestions and/or thoughts.

You can create a wrapper component that reads the path params.

Example:

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

const Breadcrumb = ({ reviewsMenuPath }) => {
  const { acronym } = useParams();

  const breadcrumbs = [
    { text: 'Reviews' },
    { text: 'History', link: `/reviewer/${reviewsMenuPath}/history` },
    { key: match.params.acronym }
  ];

  return (
    <>
      <ComponentOne title="Your completed reviews" />
      <ComponentTwo
        acronym={acronym}
        key={acronym}
        breadcrumbs={breadcrumbs}
      />
    </>
  );
};
<Routes>
  ...
  <Route
    path={`/reviewer/${reviewsMenuPath}/history/:acronym`}
    element={<Breadcrumb reviewsMenuPath={reviewsMenuPath} />}
  />
  ...
</Routes>

Another alternative is to move the useParams and const breadcrumbs logic into ComponentTwo . This is easy and trivial if ComponentTwo is already a React Function component. If it is a Class component then you'd need to either convert it to a Function component or create a custom withRouter Higher Order Component in order to access the acronym path parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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