使用 React Router 时如何将 props 传递给路由 <Link>
how to pass props to the route when using react router <Link>
我正在尝试将 props 传递给 Link 元素的路由。但是当我打开 invoiceDetails 组件时,我说 props 是未定义的。
以下是我尝试传递道具的方式。它已正确设置,因为它转到 InvoiceDetails 组件。我在 index.js
中声明了路线
<Link props={{name: 'jack', age: 25, city: 'Antwerp'}}to='/InvoiceDetails'><p>VIEW</p></Link>
并且在 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
我想使用从全局 redux 状态获取的变量将 props 传递给 invoicedetails 组件。现在静态数据很好,我猜同样的原则适用。
在state
中提及道具即可通过
<Link
to={{
pathname: "/InvoiceDetails",
state: { name: 'jack', age: 25, city: 'Antwerp'}
}}
/>
了解更多 here
要在你的下一个组件中使用它,你必须用 react-router-dom HOC withRouter
包装你的组件,或者使用他们提供的 useLocation
钩子。
EX- 在你的第二个组件中 -
import {useLocation} from "react-router-dom";
function Child() {
let data = useLocation();
console.log(data); //state would be in data.state//
}
我正在尝试将 props 传递给 Link 元素的路由。但是当我打开 invoiceDetails 组件时,我说 props 是未定义的。
以下是我尝试传递道具的方式。它已正确设置,因为它转到 InvoiceDetails 组件。我在 index.js
中声明了路线<Link props={{name: 'jack', age: 25, city: 'Antwerp'}}to='/InvoiceDetails'><p>VIEW</p></Link>
并且在 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
我想使用从全局 redux 状态获取的变量将 props 传递给 invoicedetails 组件。现在静态数据很好,我猜同样的原则适用。
在state
<Link
to={{
pathname: "/InvoiceDetails",
state: { name: 'jack', age: 25, city: 'Antwerp'}
}}
/>
了解更多 here
要在你的下一个组件中使用它,你必须用 react-router-dom HOC withRouter
包装你的组件,或者使用他们提供的 useLocation
钩子。
EX- 在你的第二个组件中 -
import {useLocation} from "react-router-dom";
function Child() {
let data = useLocation();
console.log(data); //state would be in data.state//
}