[英]ReactJS : How to read value passed in Link react-router in another functional component
I have followed the suggestion on Pass props in Link react-router我遵循了链接 react-router 中关于通行证道具的建议
I'm sending Link
value to the ReactJS functional component and while accessing it returning empty, I'm sure missing something basic here.我正在将
Link
值发送到 ReactJS功能组件,并且在访问它时返回空值,我确定这里遗漏了一些基本的东西。
This is my Route path这是我的路线路径
<Route path="/report/:id">
<ReportPage />
</Route>
The report page which is trying to get value from either query param or state param both returns empty试图从查询参数或 state 参数中获取值的报告页面都返回空
const ReportPage = (props) => {
const { query } = useParams();
const { hello } = useState()
console.log(query) // Return Empty for Try #2
console.log(hello) // Return Empty for Try #1
console.log(this.props.match.params.hello) // Undefined for
return (
<DashboardLayout>
<h2> AMI Test Reports </h2>
</DashboardLayout>
)
}
DashbaordPage which is Linking正在链接的 DashbaordPage
Tried 1 Using the state尝试 1使用 state
<Link
to={{
pathname: "/report/1",
state: {
hello: "Hello World"
}
}}>
Press Me
</Link>
Tried #2 using the query使用查询尝试#2
<Link
to={{
pathname: "/report/1",
query: "test"
}}>
Press Me
</Link>
What is the right way to access the Value passed in the Link in another functional component.在另一个功能组件中访问链接中传递的值的正确方法是什么。
useParams returns an object containing all of the available parameters. useParams 返回一个包含所有可用参数的 object。 What you currently have is useParams returning an object that contains a
params
property which is incorrect.您当前拥有的是 useParams 返回一个 object,其中包含一个不正确的
params
属性。
what you want:你想要什么:
const { id } = useParams();
As for the location state, you'd get that from useLocation, not useState.至于位置 state,您将从 useLocation 而不是 useState 获得它。
const { state } = useLocation()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.