Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm fetching news articles from The Guardian API. Article id's are like this: "world/live/2020/dec/31/coronavirus-covid-live-news-updates-vaccine-lockdown"

I need to go from article summary to article details and I'm using React Router for this. If I use const { id } = useParams(); and console log it, it gets only gets "world" form the id. How can I get the full id?

<Route path="/:id" component={ArticlePage} />

    {topStories.map((story) => (
      <Link to={`/${story.id}`}>
        <ImageCard key={story.id} story={story} />
      </Link>
    ))}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
452 views
Welcome To Ask or Share your Answers For Others

1 Answer

Issue

Path "/:id" will only match the first path "segment", i.e. "world" from "world/live/2020/dec/31/coronavirus-covid-live-news-updates-vaccine-lockdown".

Solution

If the path is "world/live/2020/dec/31/coronavirus-covid-live-news-updates-vaccine-lockdown" and you are trying to get coronavirus-covid-live-news-updates-vaccine-lockdown as the id then you need to define a route path that matches what you want to extract.

Something like

<Route path="/world/live/:year/:month/:day/:id" component={ArticlePage} />

Now using the params you can extract any of these, including the id.

const { day, id, month, year } = useParams();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...