简体   繁体   English

将道具从导航链接传递到组件 React 路由器

[英]Passing props from a navlink to a component React Router

I'm trying to pass a props from my navlink to another component, but, when I make the call from the console, I get an error我正在尝试将我的导航链接中的道具传递给另一个组件,但是,当我从控制台进行调用时,出现错误

Nav Link导航链接

<NavLink price={price} className="NavProjet" to={{
   pathname:"/boutique/checkout/",
   state: {
      price: {price},
     
    } }} >

Component Page组件页面

console.log("price",props.location.state.price)

Console error => Cannot read property 'state' of undefined控制台错误 => 无法读取未定义的属性“状态”

If someone have a solution?如果有人有解决方案? Thanks for time!感谢时间!

You're giving an object as a value to the state, for example:您将 object 作为 state 的值,例如:

price: {
  price: {
    prix: 'hello',
  }
}

So you would access it, as of right now, by console.log("price",props.location.state.price.prix) .因此,您现在可以通过console.log("price",props.location.state.price.prix)访问它。 I think you meant to do:我认为你的意思是:

state: price

?. ?. This would make it possible to do props.location.state.prix .这样就可以执行props.location.state.prix

SOLVED !解决了 !

<NavLink prix={prix} className="NavProjet" to={{
   pathname:"/boutique/checkout/",
   state: {
      prix: `${prix}`,
     
    } }} >

And Component page和组件页面

import { useLocation } from 'react-router-dom';

 const location = useLocation();
  
  console.log(location.state.prix);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM