在我的 app.js 组件中,我有一个名为“recipes”的数组,它必须包含我喜欢在路由器中呈现这些元素的元素,认为是 id。 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 组件以获得您期望的功能。你需要做两件事之一。要么将 recipe 组件设为 Route 组件,要么保持原样并将其包装在 Route Component 中并使用 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
弄清楚你得到了什么 Prop 并进行必要的调整。
关于reactjs - 将路由器 ID react 为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494905/