尝试在路由内将 Props 从一个组件传递到另一个组件,但我得到了未定义的 Props

发布于 2025-01-20 13:15:57 字数 8 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪都笑了 2025-01-27 13:15:57

如果你想通过React Router中的Link Component发送props,你必须使用其中的state prop。在导航组件中,您可以使用 location.state 访问该值。如果您想在 JSX 中使用模板文字(即在 中),您必须使用 JSX 嵌入表达式来嵌入它们。对于您的情况,您的解决方案是:
<链接到={`/dev/${dev._id}`} state={{ dev: dev }}}
在导航组件上,您可以使用以下方式访问它:

import {useLocation} from "react-router-dom"

const DevProfile = () => {
   const location = useLocation();
   const { dev } = location.state;
   // Your Logic
}

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,

import {useLocation} from "react-router-dom"

const DevProfile = () => {
   const location = useLocation();
   const { dev } = location.state;
   // Your Logic
}
我很坚强 2025-01-27 13:15:57

我假设在按钮点击按钮时会渲染Devprofile组件。您可以利用React-Router-Dom的USEE钩访问通过链接传递的道具。像这样 -

  import { useLocation } from 'react-router-dom'
    const DevProfile = () => {   
    const location = useLocation()   
    const { dev } = location.state    
    return (...) 
    }

另外,我不确定您用于链接的语法是否有效。但是我会分享我主要使用的语法 -

<Link to={`/dev/${dev._id}`} state={{ dev: dev }}>

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-

  import { useLocation } from 'react-router-dom'
    const DevProfile = () => {   
    const location = useLocation()   
    const { dev } = location.state    
    return (...) 
    }

Also, I'm not sure the syntax you used for Link is valid or not. But I'll share the syntax I mostly use-

<Link to={`/dev/${dev._id}`} state={{ dev: dev }}>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文