Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - React router - url changes, no render

Using a simple link to / route to via React browser Router.

I got it to work fine with routing to the root component (/), however it does not function as expected when trying to route to (/drink/:drinkId), though the URL changes and the page loads if I manually try to access it.

App component:

import React from "react";
import "./App.css";
import Cocktails from "./Cocktails";
import { Container } from "react-bootstrap";
import NavApp from "./Navbar";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import DrinkDetails from "./DrinkDetails";
import "./App.css";

function App() {
  return (
    <Router>
      <Container className="App-container">
        <NavApp />
        <Switch>
          <Route exact path="/">
            <Cocktails size={20} />
          </Route>
          <Route exact path="/drink/:drinkId">
            <DrinkDetails />
          </Route>
        </Switch>
      </Container>
    </Router>
  );
}

export default App;

Drink details component:

import { React, useState, useEffect } from "react";
import { Jumbotron, Button } from "react-bootstrap";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams,
} from "react-router-dom";
import axios from "axios";

function DrinkDetails() {
  let { drinkId } = useParams();
  const [drink, setDrink] = useState(null);
  const [ingrdts, setIngrdts] = useState([]);

  useEffect(() => {
    const getDrinkSpecs = async () => {
      const res = await axios.get(
        `https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${drinkId}`
      );
      let newDrink = res.data.drinks[0];
      setDrink(newDrink);
      let newIngrdts = [];
      for (let i = 1; i <= 15; i++) {
        if (newDrink[`strIngredient${i}`] != null) {
          let ingrdtVal = {};
          ingrdtVal["ing"] = newDrink[`strIngredient${i}`];
          ingrdtVal["val"] = newDrink[`strMeasure${i}`];
          newIngrdts.push(ingrdtVal);
        }
      }
      setIngrdts([...newIngrdts]);
    };
    getDrinkSpecs();
  }, [drinkId]);

  return drink ? (
    <Jumbotron>
      <h1>
        {drink.strDrink}
        <img src={drink.strDrinkThumb} />
      </h1>
      <p>Glass: {drink.strGlass}</p>
      <p>Category: {drink.strCategory}</p>
      <p>Instructions: {drink.strInstructions}</p>
      {ingrdts.map((ingrdt) => (
        <p>
          {ingrdt.ing} : {ingrdt.val}
        </p>
      ))}
      <p>
        <Button variant="primary">Learn more</Button>
      </p>
    </Jumbotron>
  ) : (
    <Jumbotron>
      <h1>Hmmm... we don't have this yet!</h1>
      <p>
        This is a simple hero unit, a simple jumbotron-style component for
        calling extra attention to featured content or information.
      </p>
      <p>
        <Button variant="primary">Learn more</Button>
      </p>
    </Jumbotron>
  );
}

export default DrinkDetails;

and this is where I use Link:

import React from "react";
import { Button, Card } from "react-bootstrap";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import "./Card.css";

function CardDrink({ data, select }) {
  return (
    <Router>
      <Card className="Cocktail-card">
        <Link to={`/drink/${data.idDrink}`}>
          <Card.Img
            variant="top"
            src={data.strDrinkThumb}
            className="Cocktail-card-img"
            onClick={() => select(data.idDrink)}
          />
        </Link>
        <Card.Body>
          <Card.Title>{data.strDrink}</Card.Title>
        </Card.Body>
      </Card>
    </Router>
  );
}

export default CardDrink;
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Remove <Router> from CardDrink component. You need only one Router at root level which you already have in App component.

Also, as a practice don't keep unused imports in your component. I see Router imported in DrinkDetails component as well.

From docs

To use a router, just make sure it is rendered at the root of your element hierarchy. Typically you’ll wrap your top-level element in a router.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...