单击时如何将数据从一个反应组件传递到另一个反应组件

[
 {
  "id": 1,
  "title": "XYZ Title",
  "body": "www.xyz.com sample hits",
  "comments": [
   {
    "id": 1,
    "postId": 1,
    "name": null,
  ,reactjs"/>
	














首页 > 解决方案 > 单击时如何将数据从一个反应组件传递到另一个反应组件

单击时如何将数据从一个反应组件传递到另一个反应组件

[
 {
  "id": 1,
  "title": "XYZ Title",
  "body": "www.xyz.com sample hits",
  "comments": [
   {
    "id": 1,
    "postId": 1,
    "name": null,
  

问题描述

单击时如何将数据从一个反应组件传递到另一个反应组件

[
 {
  "id": 1,
  "title": "XYZ Title",
  "body": "www.xyz.com sample hits",
  "comments": [
   {
    "id": 1,
    "postId": 1,
    "name": null,
    "email": "abc@cc.com",
    "body": "very simple body"
   }
 ]
}
]

我有两个 JSX 页面,一个用于帖子,第二个 JSX 页面用于评论。单击帖子时需要导航此帖子的评论页面。请参见下面的代码片段。帖子.jsx

<tbody>
{posts.map((post) => (
<tr key={post.id}>
<td>
<Link
to={`/posts/${post.id}`}
>
{post.title}
</Link>
</td>
<td>{post.body}</td>

我们如何获取和迭代相关评论数据以给出帖子 ID(单击帖子 ID 的链接时)。单击帖子的post.id到comments.jsx时如何将评论数据从posts.jsx传递到comments.jsx

评论.jsx

 <tbody>
{comments.map((comment) => (
<tr key={comment.id}>
<td>{comment.name}</td>
<td>{comment.email}</td>
<td>{comment.body}</td>

你可以像这样传递数据:

<Link to={{
  pathname: `/posts/${post.id}`,
  state: post // <---- Pass post object here
}}>{post.title}</Link>

并通过以下方式访问组件内部location

// class based component
const post_data = this.props.location.state; // <--- get access to post object
// for functional based component
let location = useLocation()
const post_data = location.state;

标签: reactjs

解决方案


您可以通过或将道具传入<Link to={{pathname: something, props: something}} /> 和使用目标组件。此外,您可以在 URL 上传递道具以重新加载,不要丢失它们。props.location.stateuseLocation() hookwithRouter HOC


推荐阅读