使用React Router <Link>时如何将道具传递到路线

时间:2019-12-24 12:38:38

标签: javascript reactjs routing react-router

我正在尝试将道具传递给Link元素的路线。但是当我打开invoiceDetails组件时,我说道具是不确定的。

下面是我尝试传递道具的方式。它已正确设置,因为它转到了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组件。现在静态数据很好,我猜想同样的原理也适用。

1 个答案:

答案 0 :(得分:1)

您可以通过在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//
}
相关问题