在我的app.js组件中,我有一个名为“食谱”的数组,它必须包含一些元素,我想在路由器中以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;
我有这两个组成部分,我不知道怎么了,我没有得到任何错误。
答案 0 :(得分:1)
我们需要在某处添加一个Route组件以获得所需的功能。您需要执行以下两项操作之一。可以使配方组件成为Route组件,或者将其保留原样并将其包装在Route Component中,然后使用渲染道具。
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
来弄清楚要获得的道具是明智的,并进行必要的调整。