在我的 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;
食谱.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 组件以获得您期望的功能。您需要做两件事之一。要么使配方组件成为 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。
or
<Route path="/recipe/:id" render={()=> <Recipe passDownSomething={this.state} />} />
进行此更改后,您就可以使用值得信赖的console.log
弄清楚你得到了什么道具并做出必要的调整。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)