How to achieve Dynamic routing in React Router 4?

后端 未结 1 800
长发绾君心
长发绾君心 2021-02-11 01:42

I have a list of articles like this:

{ this.props.articles.map(article => { return (
1条回答
  •  独厮守ぢ
    2021-02-11 02:34

    In your ArticleCard, you have to create a Link that will route to your full Article. This link will include the id of the article you are trying to render (ex. articles/${article._id})

    By writing the Route path of the component Article as articles/:id, this will allow us to catch that id when Article is rendered (accessible via this.props.match.params.id)

    Then, assuming that id is used to fetch the article from some other API, a good place to call that would be the componentDidMount of your Article component.

    Here is a small example which may help you out:

    import React from 'react'
    import {
      BrowserRouter as Router,
      Route,
      Link,
      Switch
    } from 'react-router-dom'
    
    const ParamsExample = () => (
      
        
          
          
        
      
    )
    
    const article = {
      _id: 1,
      title: 'First Article'
    };
    
    const ArticleList = () => (
      
    ); const ArticleCard = ({ article }) => (

    {article.title}

    SEE MORE
    ); class Article extends React.Component { componentDidMount() { console.log('Fetch API here: ', this.props.match.params.id); } render() { return (
    {`Fetching...${this.props.match.params.id}`}
    ); } } export default ParamsExample

    0 讨论(0)
提交回复
热议问题