Reactjs 如何在React路由器4中实现动态路由?

Reactjs 如何在React路由器4中实现动态路由?,reactjs,react-router,Reactjs,React Router,我有一个这样的文章列表: <div> { this.props.articles.map(article => { return ( <ArticleCard key={article._id} article={article} /> ) }) } </div> { this.props.articles.map(articl

我有一个这样的文章列表:

<div>
   {
       this.props.articles.map(article => {
            return (
                <ArticleCard key={article._id} article={article} />
            )
        })
    }
</div>

{
this.props.articles.map(article=>{
返回(
)
})
}
在ArticleCard组件中,我只显示文章的标题。我想把它的链接,这将创建新的URL像'文章标题',并显示内容


如何实现这一点?

在您的
文章卡中,您必须创建一个
链接
,该链接将发送到您的完整
文章
。此链接将包括您试图呈现的文章的
id
(例如
articles/${article.\u id}

通过将组件
文章
的路径写为
文章/:id
,这将允许我们在呈现
文章
时捕获该
id
(可通过
this.props.match.params.id
访问)

然后,假设使用
id
从其他API获取文章,那么调用
article
组件的
componentDidMount
就是一个好地方

下面是一个小例子,可以帮助您:

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch
} from 'react-router-dom'

const ParamsExample = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={ArticleList} />
      <Route path="/articles/:id" component={Article} />
    </Switch>
  </Router>
)

const article = {
  _id: 1,
  title: 'First Article'
};

const ArticleList = () => (
  <div>
    <ArticleCard key={article._id} article={article} />
  </div>
);

const ArticleCard = ({ article }) => (
  <div>
    <h2>{article.title}</h2>
    <Link to={`/articles/${article._id}`}>SEE MORE</Link>
  </div>
);

class Article extends React.Component {
  componentDidMount() {
    console.log('Fetch API here: ', this.props.match.params.id);
  }

  render() {
    return (
      <div>
        {`Fetching...${this.props.match.params.id}`}
      </div>
    );
  }
}

export default ParamsExample
从“React”导入React
进口{
BrowserRouter作为路由器,
路线,,
链接
转换
}从“反应路由器dom”
常量参数采样=()=>(
)
常量项目={
_id:1,
标题:“第一篇文章”
};
const ArticleList=()=>(
);
const ArticleCard=({article})=>(
{文章标题}
查看更多
);
类文章扩展了React.Component{
componentDidMount(){
log('fetchapi here:',this.props.match.params.id);
}
render(){
返回(
{`Fetching…${this.props.match.params.id}`}
);
}
}
导出默认参数示例

如果我没弄错,您希望每张卡片都有一个链接,例如:
/articles/article title
,该链接将路由到一个
article
组件,该组件将呈现
article title
的内容?(其中,
文章标题
是一个动态字符串)是的,文章标题是动态字符串,这个“内容”在哪里?我假设它是一个单独的API调用,使用
文章标题作为查询?是的,内容将是另一个API调用,使用article.\u id呈现另一个组件。现在问题出在哪里?你看过文件了吗?使用
第1条