gpt4 book ai didi

javascript - react : how to pass props through a Link from react-router-dom?

转载 作者:行者123 更新时间:2023-12-05 02:45:01 31 4
gpt4 key购买 nike

我正在尝试通过 title从 Prop 到我的 Dishes组件使用 <Link>但找不到解决方案。有什么建议吗?

import { Link } from "react-router-dom";

const Category = ({ title }) => {
return (
<Link to="/dishes">
{title}
</Link>
);
};

export default Category;

App.js看起来像这样:

return (
<Router>
<div className="App">
<Route
path="/"
exact
render={(props) => (
<Categories recipes={recipes} />
)}
/>
<Route path="/dishes" component={Dishes} />
</div>
</Router>
);

最佳答案

Link可以传递一个状态对象,该对象可以通过位置从您的组件中检索:

import { Link } from "react-router-dom";

const Category = ({ title }) => {
return (
<Link to={{ pathname: "/dishes", state: { title } }}>
{title}
</Link>
);
};

export default Category;

然后你可以从 location 属性中提取 state。但是,由于您仅在单击 Link 时才传递此值,因此如果您访问 Routestate 可以是 undefined> 直接。这样,您可能希望在这些情况下提供一个 defaultValue:

const Dishes = ({location}) => {
const { title = 'defaultValue' } = location.state || {}

return <div>{title}</div>
}

关于javascript - react : how to pass props through a Link from react-router-dom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66180064/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com