【问题标题】:Strange react-router v4 behavior with parent paths带有父路径的奇怪的 react-router v4 行为
【发布时间】:2019-04-30 22:20:21
【问题描述】:

背景故事: 我正在构建这个简单的应用程序,我想用react-router v4 让它有漂亮的网址。

我有 3 个主要组件:{Home}{List}{Hotel}

{Home} 组件 - 一个简单的组件,我可以在其中选择 countrydatefromdateto 并将自己路由到 {List}

当前路径示例:http://url.com/

{List} 组件 - 一个沉重的组件,其中包含满是链接到 /hotel/ 路线的酒店的卡片。

当前路径示例:http://url.com/list/country/?datefrom=2019-01-01?dateto=2020-01-01

{Hotel} 组件 - 应用程序的最远部分,包含酒店信息和按天划分的价格列表的重要组件。

当前路径示例:http://url.com/hotel/country/hotel-name/?datefrom=2019-01-01?dateto=2020-01-01

问题:我想要做的是替换/list/ 并使用/hotels/ 作为{List} 组件,所以我在url 结构中会有一些层次结构。

但是,一旦我尝试将 /list/ -> /hotels/ 更改为 {List} 组件路由,我的整个应用程序就会中断,并且我会收到来自 {Hotel} 组件的大量错误,这发生在我尝试将自己从{Home} 组件路由到{List}

我尝试过的: 我尝试过使用<Switch> 组件,它使{Home} -> {List} 路由工作,但是当我尝试将自己进一步路由到一个{Hotel} 组件,它实际上呈现在页面底部并且不会替换我的{List}

这是我的 app.js 文件,它给了我奇怪的行为...

import React from "react";
import { Route, BrowserRouter as Router } from "react-router-dom";

import Home from "./Home";
import List from "./List";
import Hotel from "./Hotel";

import './styles/app.scss';

class App extends React.Component {

  render() {
    return (
      <Router>
        <div className="app">
          <Route path="/" component={Home} exact />
          <Route path="/hotels/:selectedCountry/:datefrom?:dateto?" component={List} />
          <Route path="/hotels/:selectedCountry/:selectedHotel:datefrom?:dateto?" component={Hotel} />
        </div>
      </Router>
    );
  }
};

export default App;

【问题讨论】:

    标签: reactjs react-router react-router-v4


    【解决方案1】:

    HotelList 指的是同一个资源,一个酒店,但Hotel 指的是单个酒店,即单数,而List 指的是酒店的索引,即复数。通常,路由是通过单数和复数路由来完成的。

    来自 GitHub 的示例: 提交列表的 URL:https://github.com/facebook/react/commits 单个提交的 URL:https://github.com/facebook/react/commit/ec6691a6

    在你的情况下是:

    <Route path="/hotels/your-search-params here" component={List} />
    <Route path="/hotels/:hotelId:" component={Hotel} />
    

    【讨论】:

      【解决方案2】:

      您的路线定义不正确。

      例如看看路由路径/hotels/:country/:id/:fromDate/:toDate,所以像/hotels/usa/123/2019-01-01/2019-12-30 这样的url 将正确映射到路由参数,您可以在组件中访问这些值,例如this.props.match.params.id 等,但是如果您想采用查询参数方法那么你需要在/hotels?country=usa&amp;id=123&amp;fromDate=2019-01-01&amp;toDate=2019-12-30这样的两个参数之间添加&amp;登录,然后你将从window.location.href访问它并解析查询参数或使用像query-params这样的npm包来解析。在这种情况下,您的 Route 路径将只是 /hotels

      【讨论】:

        猜你喜欢
        • 2015-09-27
        • 2017-10-05
        • 1970-01-01
        • 2023-02-21
        • 2018-11-03
        • 1970-01-01
        • 2018-01-18
        • 1970-01-01
        • 2012-02-03
        相关资源
        最近更新 更多