Введите идентификатор маршрутизатора в качестве параметра - PullRequest
0 голосов
/ 22 октября 2019

В моем компоненте 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;

У меня есть эти два компонента, я не знаю, что случилось, я не получаю никакой ошибки.

1 Ответ

1 голос
/ 22 октября 2019

Нам нужно добавить компонент Route где-нибудь, чтобы получить ожидаемую функциональность. Вам нужно сделать одну из двух вещей. Либо сделайте компонент рецепта компонентом Route, либо оставьте его как есть, оберните его в компонент Route и используйте опору рендеринга.

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.

или

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

Как только вы сделаете это изменение, вы сможете использовать доверенный console.log, чтобы выяснить, что вы получаете реквизитмудрый и сделать необходимые корректировки.

...