Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - In React, how do I display a page that uses data from a specific item from a database

In my database, I have multiple exercises and I display all of them in the main page. I want to be able to click the "View Exercise" button to see information about that exercise itself.

App.js route code:

const App = () => {
    return (
      <main>
        <Switch>
          <Route path="/" component={MainPage} exact />
          <Route path="/exercises/:name" component={Exercise} exact/>
          <Route component={Error} />
        </Switch>
      </main>
  );
};

Code component that should show a specific exercise:

import React from "react";

function Exercise(props) {

  return (
    <div>
      <h1>hi {props.name} !</h1>
    </div>
  );
}

export default Exercise;

How I display the list of exercises:

function Exercises() {
  const [exercise, setExercise] = useState([]);

  useEffect(() => {
      const getAPI = async () => {
          const response = await fetch('http://localhost:8080/');
          const data = await response.json();

          try {
              console.log(data);
              setExercise(data);
          } catch (error) {
              console.log(error);
          }
      };
      getAPI();
  }, []);

  return (
    <div>
      <h2 id="exercises">List of Exercises</h2>
      <Row>
        {exercise.map((data) => (
          <ExerciseCard
            key = {data._id}
            name = {data.name}
            img = {data.image}
          />
        ))}
      </Row>
    </div>
  );
}

export default Exercises;

The button link:

<Link to= {{
  pathname: `/exercises/${props.name}`
  }}
>

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

1 Answer

0 votes
by (71.8m points)

If I understand the question correctly, you're trying to pass an exercise name to the Exercise component via URL query parameter.

In this case you could use useParams hook from react-router. So the component becomes:

import React from "react";
import { useParams } from "react-router";

function Exercise(props) {
  const { name } = useParams();

  return (
    <div>
      <h1>hi {name} !</h1>
    </div>
  );
}

export default Exercise;

And the name for the name parameter is set in route declaration <Route path="/exercises/:name" component={Exercise} exact/>

If you're going to display more data than a name, you could consider doing an API call inside useEffect hook to get the details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...