I am working with Hacker News API and now I can link to my Comments.js
with the ID of the story in the URL like this
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>
{
EDIT: I have my Comments.js
like this
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>
)
}
I need to know how I can render the data in my Comments.js
component similar to how I am doing with the story title and author using the prop that is passed in on the url.
Given the comments route path is defined as path="/comments/:commentId"
, access the id from the match
prop.
this.props.match.params.commentId
If you need to send state with the route push, it is sent in the link's to
prop as an object specifying the pathname
and state
to be sent to the new route.
to={{ pathname: `/comments/${storyID}`, state: { data } }}
Access from the location
prop.
this.props.location.state.data
data can be anything valid as an object payload
edit
Assuming Comments
is rendered as such:
<Route path="/comments/:id" component={Comments} />
Then unpack the id
from the received match
prop:
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>
);
}
<Link to={{
pathname: `/comments/${storyID}`,
state: {
yourData: 'fooBar'
}
}}>{kids.length}</Link>
and inside your component you want to render the data:
const { yourData} = this.props.location.state
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.