reactjs - React:如何从React 路由器传递道具?
问题描述
我正在使用 Hacker News API,现在我可以Comments.js
使用 URL 中的故事 ID 链接到我,如下所示
export default function Story ({storyID}) {
const [story, setStory] = useState({});
useEffect(()=> {
getStoryTitle(storyID).then(data => data && data.url && setStory(data));
});
const kids = story.kids ? story.kids: [];
const author = story.by;
return (
<div className="story-wrapper">
<a className="a-tag" href={story.url}>
<p className="story-title">{story.title}</p>
</a>
<p className="story-author"><strong>By: {story.by}</strong> on {timeFormat(story.time)}</p>
<p className="story-comments"><Link to={`/comments/${storyID}`}>{kids.length}</Link> Comments</p>
{
编辑:我Comments.js
喜欢这样
import React, {useState, useEffect} from 'react'
import {getStoryTitle} from '../API.js'
const {comment}
export default function Comments({storyID}) {
const [comment, setComment] = useState({});
useEffect(()=> {
getStoryTitle(storyID).then(data => setComment(data))
}, [])
return (
<ul>
<li>{storyID}</li>
</ul>
)
}
我需要知道如何在我的Comments.js
组件中呈现数据,类似于我使用在 url 上传递的道具来处理故事标题和作者的方式。
解决方案
给定评论路由路径定义为,从proppath="/comments/:commentId"
访问 id 。match
this.props.match.params.commentId
如果您需要通过路由推送发送状态,它会在链接的to
prop 中作为指定pathname
和的对象state
发送到新路由。
to={{ pathname: `/comments/${storyID}`, state: { data } }}
从location
道具访问。
this.props.location.state.data
数据可以是任何有效的对象有效载荷
编辑
假设Comments
呈现如下:
<Route path="/comments/:id" component={Comments} />
id
然后从收到的match
道具中解压:
import React, { useState, useEffect } from 'react';
import { getStoryTitle } from '../API.js';
export default function Comments({ match }) {
const { id } = match.params;
const [comment, setComment] = useState({});
useEffect(()=> {
getStoryTitle(id).then(data => setComment(data));
}, []);
return (
<ul>
<li>{id}</li>
</ul>
);
}
推荐阅读
- java - 如何使用 Android 电源配置文件 XML 文件来估计系统级电源使用情况?
- r - 迭代:=跨R中的列赋值
- ios - Swift - Firestore 自动创建集合/文档
- php - 在邮递员中使用 php curl 将文件上传到 Nextcloud 但上传的文件为空
- python-3.x - 最佳 Python GloVe 词嵌入包
- reactjs - useEffect 中的无限循环,useEffect 中的 async/await
- python - 尝试用 Python 重新创建一个名为“去波士顿”的骰子游戏
- gnupg - 您如何使用 gpg 验证加密和签名的文件?
- r - 我可以控制 tidyjson 如何加入嵌套数组吗?
- regex - 用正则表达式分隔单词(不按特定顺序)