React Router V4动态参数

时间:2019-04-04 09:11:11

标签: reactjs typescript react-router-v4

我需要在使用reac-router v4的Reac应用程序中进行动态路由。 我要建立以下地址

http://localhost:7777/ oceanside-yaht-club /预订/搜索

oceanside-yaht-club 可以动态更改的位置,具体取决于我们的客户。

但这就是我现在尝试的结果:

http://localhost:7777/oceanside-yaht-club/:pathParam/booking/search

这是我尝试的方式:

export enum Routes
{
    Home = '',
    BookingSearch = 'booking/search',
    BookingOffers = 'booking/offers',
    BookingExtras = 'booking/extras',
    BookingContactDetails = 'booking/contact',
    BookingBoatDetails = 'booking/boat',
    BookingPayment = 'booking/payment',
    BookingComplete = 'booking/complete',
    BookingClose = 'booking/close'
}

export module Urls
{
    export const home = `/${Routes.Home + ':pathParam?'}`;
    export const bookingSearch = ':pathParam' + `/${Routes.BookingSearch}`;
    export const bookingOffers = `/${Routes.BookingOffers}`;
    export const bookingExtras = `/${Routes.BookingExtras}`;
    export const bookingContactDetails = `/${Routes.BookingContactDetails}`;
    export const bookingBoatDetaisl = `/${Routes.BookingBoatDetails}`;
    export const bookingPayment = `/${Routes.BookingPayment}`;
    export const bookingComplete = `/${Routes.BookingComplete}`;
    export const bookingClose = `/${Routes.BookingClose}`;
}

export const IndexRoutes = () =>
    <React.Fragment>
        <Route exact path={ Urls.home } component={ App } />
        <Route exact path={ Urls.bookingSearch } component={ Search } />
        <Route exact path={ Urls.bookingOffers } component={ Offers } />
        <Route exact path={ Urls.bookingExtras } component={ Extras } />
        <Route exact path={ Urls.bookingContactDetails } component={ ContactDetails } />
        <Route exact path={ Urls.bookingBoatDetaisl } component={ BoatDetails } />
        <Route exact path={ Urls.bookingPayment } component={ Payment } />
        <Route exact path={ Urls.bookingComplete } component={ Complete } />
        <Route exact path={ Urls.bookingClose } component={ WindowsCloseDialog } />
    </React.Fragment>

这就是我推送路由器历史记录的方式

const url: string = `${this.store.state.marinaData.MarinaUrlName}/${Urls.bookingSearch}`;
// const url: string = `oceanside-yaht-club/${Urls.bookingSearch}`; //for test
this.props.history.push(url);

我什至尝试过this正则表达式,但没有弄清楚如何在我的代码中实现

thnx

1 个答案:

答案 0 :(得分:1)

在将url传递到history.push时,不能直接使用Route path参数,而是需要一个完整的链接。

您可以将代码更改为

const url: string = `${this.store.state.marinaData.MarinaUrlName}/${Routes.BookingSearch}`;

this.props.history.push(url);