尝试在路由内将 Props 从一个组件传递到另一个组件,但我得到了未定义的 Props
continue
this is the code of the first component that i'm send the props from it
const Devcard = ({dev}) => {
return (
<Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}>
<Button variant="primary">Learn More</Button>
</Link>
</Card.Body>
</Card>
);
};
and this is the component that i'm getting in it the Props.
i'm getting undefined Props in here
const DevProfile = (props) => {
console.log(props.location.devProps.dev);
return (
<div></div>
)
please check my code , thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想通过React Router中的Link Component发送props,你必须使用其中的state prop。在导航组件中,您可以使用 location.state 访问该值。如果您想在 JSX 中使用模板文字(即在
中),您必须使用 JSX 嵌入表达式来嵌入它们。对于您的情况,您的解决方案是:
<链接到={`/dev/${dev._id}`} state={{ dev: dev }}}
。在导航组件上,您可以使用以下方式访问它:
If you want to send props through Link Component in React Router, you must use the state prop in it. And at the navigated Component you access that value using location.state. And If you want to use template literals in your JSX(i.e., in
<Link />
) you must embed them with JSX Embedded Expression. In your case, your Solution is:<Link to={`/dev/${dev._id}`} state={{ dev: dev }}}
.On Navigated Component, you access this using,
我假设在按钮点击按钮时会渲染Devprofile组件。您可以利用React-Router-Dom的USEE钩访问通过链接传递的道具。像这样 -
另外,我不确定您用于链接的语法是否有效。但是我会分享我主要使用的语法 -
I'm assuming DevProfile component gets rendered on the button click. You can leverage react-router-dom's useLocation hook to access props passed via Link. Like this-
Also, I'm not sure the syntax you used for Link is valid or not. But I'll share the syntax I mostly use-