[英]How to get the value of the passed data from <Link/> component in my next functional component page in Reactjs
I have two pages, i want to pass data from one functional component to the other, i am trying to achieve this by using <Link/>
but i don't know how i would retrieve this in my other page:我有两页,我想将数据从一个功能组件传递到另一个,我试图通过使用
<Link/>
来实现这一点,但我不知道如何在我的另一个页面中检索它:
here is my code:这是我的代码:
FirstPage:第一页:
const CustomerListResults = () => {
<Link
to={{
pathname: "/app/CustomerDetails",
data: id // your data array of objects
}}>
<Button
color="primary"
variant="contained"
>
Expand
</Button>
</Link>
}
My Second Page that i need the data in:我需要数据的第二页:
const CustomerProfile = () => {
// here i want to get the id i passed in the <Link/> component
}
my Routes.js file:我的 Routes.js 文件:
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <Account /> },
{ path: 'customers', element: <CustomerList /> },
{ path: 'CustomerDetails', element: <CustomerDetails /> },
{ path: 'ReportDetails', element: <ReportDetails /> },
{ path: 'report', element: <ReportList /> },
{ path: 'freight', element: <FreightList /> },
{ path: 'dashboard', element: <Dashboard /> },
{ path: 'analytics', element: <Analytics /> },
{ path: 'products', element: <ProductList /> },
{ path: 'settings', element: <Settings /> },
{ path: '*', element: <Navigate to="/404" /> }
]
},
{
path: '/',
element: <MainLayout />,
children: [
{ path: 'login', element: <Login /> },
{ path: 'register', element: <Register /> },
// { path: '404', element: <NotFound /> },
{ path: '/', element: <Navigate to="/login" /> },
{ path: '*', element: <Navigate to="/app/dashboard" /> }
]
}
];
export default routes;
If I'm not wrong you want to pass data from Pages linked with the Router, Route and Link.如果我没猜错,您希望从与路由器、路由和链接链接的页面传递数据。
To accomplish that I use 'react-router-dom' insthead of 'react-router'.为了实现这一点,我使用了“react-router”的“react-router-dom”insthead。
When I am on a Page and I programmatically push another with : history.push() you can even pass the state, and inside that you can put whatever object you want.当我在一个页面上并以编程方式推送另一个页面时:history.push() 你甚至可以传递状态,在里面你可以放置任何你想要的对象。
To retrive it on the other Page you have to use : useLocation().state要在另一个页面上检索它,您必须使用:useLocation().state
It will return the state object passed before.它将返回之前传递的状态对象。 So basically you can go like :
所以基本上你可以这样:
history.push({location:"path/to/next/page", state : { obj : "value1",obj2 : "value2"}); history.push({location:"path/to/next/page", state : { obj : "value1",obj2 : "value2"});
and in the next page you can destructure at the start like :在下一页中,您可以在开始时进行解构,例如:
const {obj,obj2} = useLocation().state; const {obj,obj2} = useLocation().state;
I'm sorry I can't use the "code mode" because I'm from mobile.很抱歉我不能使用“代码模式”,因为我来自手机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.