栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在您的服务器中

ArticleCard
,您必须创建一个
link
将路由到您的完整主机
Article
。这个环节将包括
id
你试图渲染的文章(前。
articles/${article._id}

通过

Route
将组件的路径编写
Article
articles/:id
,这将使我们能够捕获渲染
id
时的
Article
内容(可通过访问
this.props.match.params.id

然后,假设

id
用于从一些其他的API获取的文章,一个好地方调用这将是
componentDidMount
你的
Article
组件。

这是一个小示例,可能会对您有所帮助:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406612.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号