简体   繁体   中英

React Router loads URL in address bar but doesn't load component

Codesandbox link here .

When a user clicks on a link, it should load the component in '/details'. However on click, it does load /details in the address bar but the component doesn't actually load. It only loads on going separately to /details manually in the address bar.

Routes.js

const Routes = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={App} />
        <Route exact path="/details" component={MachineDetail} />
      </Switch>
    </BrowserRouter>
  );
};

MachineCard.js

export default function MachineCard({ image, title, weight, power }) {
  return (
    <>
      <div className="col-lg-4">
        <div className="card">
          <Router>
            <Link to="/details">
              <img className="img-fluid" src={image} alt={title} />
              <h2>{title}</h2>
            </Link>
          </Router>
          <p>Operating weight: {weight}</p>
          <p>Power: {power}</p>
        </div>
      </div>
    </>
  );
}

Any idea why it won't load the '/details' component in the browser?

This issue is that you have multiple routers in your app, but you only need one. Since you already have the router defined in your index file, you can go ahead and remove it from MachineCard.js .

Your MachineCard.js component can therefore be simplified to this:

export default function MachineCard({ image, title, weight, power }) {
  return (
    <>
      <div className="col-lg-4">
        <div className="card">
          <Link to="/details">
            <img className="img-fluid" src={image} alt={title} />
            <h2>{title}</h2>
          </Link>
          <p>Operating weight: {weight}</p>
          <p>Power: {power}</p>
        </div>
      </div>
    </>
  );
}

I think your problem is incorrect naming. In your route files you are using MachineDetail but you are exporting MachineCard.

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