首页 > 解决方案 > 如何用反应处理无限链接

问题描述

我目前正在构建一个基于 ReactJS 和 react-router 的食谱书网站。我所有的信息都保存在 JSON 中,我正在使用 axios 处理所有这些信息。现在我的问题是,我有一个包含所有食谱的网格,当我单击一个时,它使用链接将我重定向到另一个页面,如下所示:
<Link to={'/' + name} className="recipe-styler" id={name}>

我如何重定向它,以便它打开一个页面并加载该页面的信息。例如,我正在考虑将其重定向到 /detailedRecipe 并通过链接解析所有信息,但我不知道这是否可能。

标签: reactjsreact-routerreact-router-dom

解决方案


这是动态路由与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

推荐阅读