![](/img/trans.png)
[英]How to pass props/params/state to a Route with Link in React Router 5.2.0?
[英]how to pass props to the route when using react router <Link>
我正在嘗試將道具傳遞給 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 狀態獲取的變量將道具傳遞給 invoicedetails 組件。 現在靜態數據很好,我想同樣的原則也適用。
你可以通過在state
提及 props 來傳遞它
<Link
to={{
pathname: "/InvoiceDetails",
state: { name: 'jack', age: 25, city: 'Antwerp'}
}}
/>
並且要在您的下一個組件中使用它,您必須使用 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//
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.