React Router id 作为参数

React Router id as parameter

在我的 app.js 组件中,我有一个名为 "recipes" 的数组,它必须包含我喜欢的元素,以便在路由器中呈现这些元素(认为是一个 id)。 App 组件应该通过配方组件呈现它。

我这里有一些代码,但它不能正常工作。我整晚都试过了,但我找不到错误。我是新手,所以也许你可以看到我看不到的错误。

App.js

    import React, { Component } from "react";
import "./App.css";
import Recipes from "./components/Recipes";
import { Router } from "@reach/router";
import Recipe from "./components/Recipe ";
import Nav from "./components/Nav";
import About from "./components/About";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      recipes: [
        {
          id: 1,
          title: "Drink",
          image: "https://picsum.photos/id/395/200/200"
        },
        { id: 2, title: "Pasta", image: "https://picsum.photos/id/163/200/200" }
      ]
    };
  }

  getRecipe(id) {
    //Number(id)

    return this.state.recipes.find(e => e.id === Number(id));
  }

  render() {
    return (
      <React.Fragment>
        Recipes
        {/*Sending the props from this component to the recipes component so it can be rendered there. And shown here
               <Recipes recipes={this.state.recipes}></Recipes>
          */}
        <Nav></Nav>
        <Router>
          <About path="/about"></About>
          <Recipe
            path="/recipe/:id"
            loadRecipe={id => this.getRecipe(id)}
          ></Recipe>
        </Router>
      </React.Fragment>
    );
  }
}

export default App;

Recipe.js

import React, { Component } from "react";

class Recipe extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // See App.js for more details. loadRecipe is defined there.
      recipe: this.props.loadRecipe(this.props.id)
    };
  }

  render() {
    // In case the Recipe does not exists, let's make it default.
    let title = "Recipe not found";

    // If the recipe *does* exists, make a copy of title to the variable.
    if (this.state.recipe) {
      title = this.state.recipe.title;
    }

    return (
      <React.Fragment>
        <h1>The recipe:</h1>
        <p>{title}</p>
        {/* TODO: Print the rest of the recipe data here */}
      </React.Fragment>
    );
  }
}

export default Recipe;

我有这两个组件,我不知道出了什么问题,我没有收到任何错误。

我们需要在某处添加 Route 组件以获得您期望的功能。你需要做两件事之一。要么将 recipe 组件设为 Route 组件,要么保持原样并将其包装在 Route 组件中并使用 render prop。

const Recipe = (props) => {
  <Route {...props}>
     // This is where your actual recipe component will live
  </Route>
}

那你就可以

<Recipe
  path="/recipe/:id"
  loadRecipe={this.getRecipe}>
</Recipe>

对于 loadRecipe 部分,您可能只想将函数向下传递,然后在 Recipe 组件中使用它。您应该从 Route 组件中获取 id。

  <Route path="/recipe/:id" render={()=> <Recipe passDownSomething={this.state} />} />

进行此更改后,您可以使用可信赖的 console.log 来弄清楚您获得的道具是什么,并做出必要的调整。