Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

typescript - Routing - Reactjs - only first Route works

I want to create reusable Route component

import React from 'react';
import { Route } from 'react-router-dom';

interface ITProffesion {
  proffesion: string;
}

export const ITRoleRouter: React.FC<ITProffesion> = ({ proffesion }) => (
  <Route exact path={`/${proffesion}`} key={proffesion}>
    <p>Works {proffesion}</p>
  </Route>
);

but when i want to use it - only first Route works - example (only backend works - is's a test I will download data from api):

export const App: React.FC<{}> = () => (

      <Router>
        <Switch>
          <Route exact path="/">
            <DemoContainer />
          </Route>
          <ITRoleRouter proffesion="backend" />
          <ITRoleRouter proffesion="frontend" />
        </Switch>
      </Router>
);

What is wrong? Can I use react router in this way? Thanks,Asia

question from:https://stackoverflow.com/questions/65939356/routing-reactjs-only-first-route-works

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason for this behavior is that the Switch component uses the path and from props of its children components to check whether there is a route match, which decides what is rendered.

The ITRoleRouter component instances don't have these props but are children of the Switch component.

Because both ITRoleRouter instances don't have these props it will instead match the first instance.

So instead you could do something like this:

interface ITProffesion {
  path: string;
  proffesion: string;
}

const ITRoleRouter: React.FC<ITProffesion> = ({ path, proffesion }) => (
  <Route exact path={path} key={proffesion}>
    <p>Works {proffesion}</p>
  </Route>
);

const App: React.FC<{}> = () => (
  <Router>
    <Switch>
      <Route exact path="/">
        <DemoContainer />
      </Route>
      <ITRoleRouter path="/backend" proffesion="backend" />
      <ITRoleRouter path="/frontend" proffesion="frontend" />
    </Switch>
  </Router>
);

Check out this Github issue for more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...