【问题标题】:In React, how do I display a page that uses data from a specific item from a database在 React 中,如何显示使用数据库中特定项目的数据的页面
【发布时间】:2021-01-11 08:19:28
【问题描述】:

在我的数据库中,我有多个练习,我将所有练习都显示在主页上。我希望能够单击“查看练习”按钮以查看有关该练习本身的信息。

App.js 路由代码:

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

应该显示特定练习的代码组件:

import React from "react";

function Exercise(props) {

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

export default Exercise;

我如何显示练习列表:

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;

按钮链接:

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

【问题讨论】:

  • 您是否只是试图在Exercise 组件的标题中显示练习名称?或者你想要整个data/exercise 对象?如果您只需要name 路由参数,那么使用useParams 在路由组件中访问它。

标签: reactjs react-router


【解决方案1】:

如果我正确理解了这个问题,您正在尝试通过 URL 查询参数将练习名称传递给 Exercise 组件。

在这种情况下,您可以使用来自react-routeruseParams 挂钩。所以组件变成:

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;

并且name参数的名称在路由声明&lt;Route path="/exercises/:name" component={Exercise} exact/&gt;中设置

如果您要显示比名称更多的数据,您可以考虑在 useEffect 挂钩中进行 API 调用以获取详细信息。

【讨论】:

    猜你喜欢
    • 2013-04-28
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多