我无法获得 props.match.params.id。据说道具是未定义的

use*_*145 0 reactjs

我试图从 URL(使用 props.match.params.id)获取id并将其传递给一个变量以重用它。但是 props 是未定义的。我不知道为什么。

任何人都可以看到我是否做错了什么?

import React, { useState, useEffect } from "react";
import axios from "axios";

export default function Recipes() {
  const [recipes, setRecipes] = useState([]);
  useEffect(() => {
    const id = props.match.params.id;
    const getRecipes = async () => {
      const url = `http://localhost:8000/user/recipes/${id}`;
      const result = await axios.get(url);

      setRecipes(result.data);
      console.log("test", recipes);
    };
    getRecipes();
  }, []);

  return (
    <div>
      {recipes.map(recipe => (
        <p>{recipe.title}</p>
      ))}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*yle 5

您需要为此使用useParams钩子react-router-dom

尝试这个:

...
import { useParams } from 'react-roouter-dom'

export default function Recipes() {
  ...
  const { id } = useParams()

  useEffect(() => {
    ...
  }, [id])
  ...
}
Run Code Online (Sandbox Code Playgroud)