【问题标题】:React Router root element with param使用参数反应路由器根元素
【发布时间】:2017-07-29 16:36:54
【问题描述】:

我正在重写一个 ASP.NET MVC 应用程序以在 TypeScript 中使用 React 和 Redux。对于路由,我使用的是 React Router。该站点使用根参数来标识客户的组织。

示例; www.oursite.com/:organizationId 带有深层链接,例如 www.oursite.com/:organizationId/overviewwww.oursite.com/:organizationId/account/:accountId

我已经如下配置了 React 路由器

import * as React from 'react';
import { Router, Route, IndexRoute, HistoryBase } from 'react-router';
import { Layout } from './components/Layout';
import Home from './components/Home';
import OverView from './components/OverView';
import Account from './components/Account';

export default <Route path='/:organizationId' component={ Layout }>
    <IndexRoute components={{ body: Home }} />
    <Route path='overview' components={{ body: OverView }} />
    <Route path='account/:accountId' components={{ body: Account }} />
</Route>;

这可行,但页面上的任何链接组件都不起作用,因为应用程序/页面的根仍然是 /。

例如

<Link to={'/overview'} activeClassName='active' />

在帐户控制链接上指向 www.oursite.com/overview,而不是 www.oursite.com/:organizationId/overview

有没有办法配置 React Router 以将 /:organizationId/ 视为根?

【问题讨论】:

    标签: reactjs typescript react-router react-redux-form


    【解决方案1】:

    如果您查看 react-router 文档,它看起来像相对链接,因为 react-router 不支持字符串。目前仅支持绝对链接。

    https://github.com/ReactTraining/react-router/blob/master/docs/API.md#link

    但是,我认为您正在寻找的是参数。 React-router 将参数作为道具传递给连接到路由的每个组件。例如,在您的概览组件中应该有 params 道具。你应该能够做类似的事情

    <Link to={`/${this.props.params.organizationId}/overview`></Link>

    如果这有帮助,请告诉我!

    【讨论】:

    • 这很好用!因为我使用的是 TypeScript,所以我必须将 { params: { organizationId: string }} 添加到适用的 props 类型声明中才能访问 this.props.params
    猜你喜欢
    • 2017-06-28
    • 2018-06-11
    • 2017-08-11
    • 1970-01-01
    • 2017-06-14
    • 2017-07-16
    • 2021-04-27
    • 2020-10-02
    相关资源
    最近更新 更多