简体   繁体   English

使用反应路由器时如何将道具传递给路线<Link>

[英]how to pass props to the route when using react router <Link>

i'm trying to pass props to the route of the Link element.我正在尝试将道具传递给 Link 元素的路线。 But when I open the invoiceDetails components, i says props is undefined.但是当我打开 invoiceDetails 组件时,我说 props 是未定义的。

Below is how I'm trying to pass the props.下面是我试图传递道具的方式。 It is correctly setup because it goes to the InvoiceDetails component.它设置正确,因为它转到 InvoiceDetails 组件。 I declared the routes in my index.js我在 index.js 中声明了路由

<Link props={{name: 'jack', age: 25, city: 'Antwerp'}}to='/InvoiceDetails'><p>VIEW</p></Link>

And in the InvoiceDetails component在 InvoiceDetails 组件中

import React from 'react'
import DashboardHeader from '../dashboardHeader/dashboardHeader'
import { Link } from 'react-router-dom'
function InvoiceDetails(){
console.log(props)
    return(
        <div className='w-10/12 bg-gray-300 float-right min-h-screen'>
          <div className='w-10/12 fixed z-50'>
.........
)
}
export default invoiceDetails

I would like to pass the props to the invoicedetails component using variables that I get from a global redux state.我想使用从全局 redux 状态获取的变量将道具传递给 invoicedetails 组件。 For now the static data is fine, the same principles apply I guess.现在静态数据很好,我想同样的原则也适用。

You can pass it by mentioning the props in state你可以通过在state提及 props 来传递它

<Link
  to={{
    pathname: "/InvoiceDetails",
    state: { name: 'jack', age: 25, city: 'Antwerp'}
  }}
/>

Read about it more here在这里阅读更多信息

And to use it in your next component you have to either wrap your component with a react-router-dom HOC withRouter or use useLocation hook they have provided.并且要在您的下一个组件中使用它,您必须使用 react-router-dom HOC withRouter包装您的组件,或者使用他们提供的useLocation钩子。

EX- In your second component - EX- 在你的第二个组件中 -

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

function Child() {
 let data = useLocation();
 console.log(data); //state would be in data.state//
}

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

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