[英]How do I link React components to unique URLS based on input props?
I'm making a recipe website in React and trying to link each recipe to a unique URL.我正在用 React 创建一个食谱网站,并尝试将每个食谱链接到一个独特的 URL。
I have a database with recipes, and one of them renders as a <Recipe/>
component, based on which button is clicked (These buttons are automatically generated as well).我有一个包含食谱的数据库,其中一个根据单击的按钮呈现为
<Recipe/>
组件(这些按钮也会自动生成)。
import Recipe from './recipe.js'
import Recipes from '../data/recipes.js'
export default function Main(){
const [currentRecipe, setCurrentRecipe] = React.useState(<div></div>)
//Below generates all buttons for all recipes available, with corresponding parameter for function call
const allButtons = Recipes.map(recipe => {
return(
<button className="recipeButton" onClick={()=>RenderRecipe(recipe.Name)}>{recipe.Name}</button>
)
})
//Below function then generates a recipe based on which button was clicked
function RenderRecipe(recipeName){
Recipes.map(recipe => {
if (recipe.Name===recipeName){
const newRecipe =
<Recipe
name={recipe.Name}
ingredients={recipe.Ingredients}
instructions={recipe.Instructions}
numberOfPeople={8}
/>
setCurrentRecipe(newRecipe)
}
})
}
return (
<div>
{allButtons}
{currentRecipe}
</div>
)
}
The recipe display is working, but everything is happening on the same URL, and I want users to be able to bookmark recipes in their browser and go back and forth between recipes.食谱显示工作正常,但一切都发生在同一个 URL 上,我希望用户能够在他们的浏览器中为食谱添加书签,并且 go 在食谱之间来回切换。 Is there a way to do something like the following:
有没有办法执行以下操作:
'pancakesbutton'.onclick("render the pancakes <Recipe/>
& change URL to index.html/pancakes)" 'pancakesbutton'.onclick("渲染煎饼
<Recipe/>
并将 URL 更改为 index.html/pancakes)"
(preferably in a way that the website knows that index.html/pancakes should display the pancakes recipe) (最好以网站知道 index.html/pancakes 应该显示煎饼食谱的方式)
I've looked into react-router-dom, but it seems that it requires you to make separate files for every recipe.我研究了 react-router-dom,但似乎它需要您为每个配方制作单独的文件。 Is there a way to avoid that?
有没有办法避免这种情况?
Thanks in advance!提前致谢!
You can move the actual recipe display to a different component and you can define all recipe routes to that component.您可以将实际配方显示移动到不同的组件,并且可以定义该组件的所有配方路径。 So based on the URL path you can write the logic of displaying corresponding recipes.
所以基于 URL 路径可以编写显示对应菜谱的逻辑。
<Route exact path={["/pancakes", "/another-recipe"]}>
<RecipeComponent />
</Route>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.