如何在 React Router 4 中实现动态路由? [英] How to achieve Dynamic routing in React Router 4?
问题描述
我有一个这样的文章列表:
{this.props.articles.map(article => {返回 (<ArticleCard key={article._id} article={article}/>)})}
在 ArticleCard 组件中,我只显示文章的标题.我想添加一个指向它的链接,它会创建像文章标题"这样的新 URL 并显示内容.
如何实现这一目标?
在您的 ArticleCard
中,您必须创建一个 Link
将路由到您的完整 文章
.此链接将包含您尝试呈现的文章的 id
(例如 articles/${article._id}
)
通过将组件Article
的Route
路径写成articles/:id
,这将使我们能够捕捉到那个id
当 Article
呈现时(可通过 this.props.match.params.id
访问)
然后,假设 id
用于从其他一些 API 获取文章,调用它的好地方是 Article<的
componentDidMount
/code> 组件.
这里有一个小例子,可以帮到你:
从 'react' 导入 React进口 {BrowserRouter 作为路由器,路线,关联,转变来自'反应路由器-dom'const ParamsExample = () =>(<路由器><开关><路由精确路径="/" component={ArticleList}/><Route path="/articles/:id" component={Article}/></开关></路由器>)const 文章 = {_id: 1,标题:'第一篇'};const ArticleList = () =>(<div><ArticleCard key={article._id} article={article}/>
);const ArticleCard = ({ 文章 }) =>(<div><h2>{article.title}</h2><Link to={`/articles/${article._id}`}>查看更多</Link>
);类文章扩展了 React.Component {componentDidMount() {console.log('在这里获取 API:', this.props.match.params.id);}使成为() {返回 (<div>{`正在获取...${this.props.match.params.id}`}
);}}导出默认参数示例
I have a list of articles like this:
<div>
{
this.props.articles.map(article => {
return (
<ArticleCard key={article._id} article={article} />
)
})
}
</div>
In the ArticleCard component, I'm only showing the title of my article. I want to put a link to it which would create new URL like 'article-title' and show the content.
How to achieve this?
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 = () => (
<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 Router 4 中实现动态路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!