reactjs - 如何用反应处理无限链接
问题描述
我目前正在构建一个基于 ReactJS 和 react-router 的食谱书网站。我所有的信息都保存在 JSON 中,我正在使用 axios 处理所有这些信息。现在我的问题是,我有一个包含所有食谱的网格,当我单击一个时,它使用链接将我重定向到另一个页面,如下所示:
<Link to={'/' + name} className="recipe-styler" id={name}>
我如何重定向它,以便它打开一个页面并加载该页面的信息。例如,我正在考虑将其重定向到 /detailedRecipe 并通过链接解析所有信息,但我不知道这是否可能。
解决方案
这是动态路由与react-router-dom和使用匹配参数的组合。
首先,假设您在应用程序中有 3 个路由,列表视图、详细信息视图和一个备用路由(例如错误页面)。它看起来像这样:
<Router>
<Switch>
<Route exact path="/recipes" component={ListComponent} />
<Route path="/recipes/:id" component={DetailsComponent} />
<Route component={ErrorPage} />
</Switch>
</Router>
现在,您可以将网格内的链接设置为如下所示:
<Link to={`/recipes/${item.id}`} className="recipe-styler" />
最后,当您单击链接时,路由器会将 DetailsComponent 重定向到您,您可以像这样获取链接 id。
export class DetailsComponent extends React.Component {
componentDidMount() {
const { match } = this.props;
if (match) {
// This line is pseudocode.
// Use the id to get the item details from api, redux or wherever.
api.get(params.id)
}
}
render() {
...
}
}
路由器在解析路由时会注入 match.params 对象。来自 params 对象的道具名称取决于您在路由器声明中如何命名它,例如
<Route path="/recipes/:recipeId" component={DetailsComponent} /> // params.recipeId
<Route path="/recipes/:id" component={DetailsComponent} /> // params.id
推荐阅读
- oracle - 使用动态更新查询更新 Ledger_stat 表中的天数列的值
- c# - 未在多线程程序中读取正确的属性值
- ajax - parsererror SyntaxError: 位置 0 的 JSON 中的意外标记 <
- java - 从泛型类型参数中检索高级信息
- xml - 为 Coldfusion 应用程序的 SSO 计算 XML 元数据中的 DigestValue 和 SignatureValue
- regex - 正则表达式搜索 von Bibtex 文件以提取捕获组中的引用键和标题
- javascript - 有一个按钮来控制时间线 GSAP 动态定位增量计数器
- python - Selenium 找不到链接的元素
- docker - 当 env 中未设置变量时,docker-compose 在随机端口上公开
- java - Bouncy Castle - 如何从 JceOpenSSLPKCS8DecryptorProviderBuilder 获取公钥信息