【问题标题】:React Router - Route With Optional Params Not WorkingReact Router - 带有可选参数的路由不起作用
【发布时间】:2017-05-08 21:27:28
【问题描述】:

我正在使用 react 和 react-router。在我的反应路由器配置中,我想添加一个将接受以下 URL 的路由:http://localhost:7000/example/GUID 其中 GUID 是当时登录的用户的 GUID。

我正在使用 WebPack。

我去了 react-router 文档:https://github.com/ReactTraining/react-router/blob/master/docs/guides/RouteMatching.md#path-syntax

但是由于某种原因这不起作用,也许我错过了一些东西。

这是我的反应路由器配置:

import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from "react-router";
import Main from "../containers/main.js";
import Home from "../containers/home.js";
import Example from "../containers/exampleComponent.js";

var Routes = (
    <Router history={browserHistory}>
        <Route path="/" component={Main}>
            <IndexRoute component={Home} />
            <Route path="/example(/:guid)" component={Example} />
        </Route>
    </Router>
);

module.exports = Routes;

当我转到http://localhost:7000/example 时,它工作正常,它会加载示例组件。

但是当我转到http://localhost:7000/example/GUID 时,它不起作用。事实上,它不会加载任何东西。根据文档,路由路径中的“()”表示它是可选的。

我还需要做些什么来完成这项工作吗?我一直在摸索这个……

编辑:请在此处查看我的 github 项目:https://github.com/FredM7/react-base 项目包含问题。

【问题讨论】:

    标签: reactjs webpack react-router


    【解决方案1】:

    我也在使用这样的路径 path: 'cn/*/cid/(:catZeroId)(/:catOneId)(/:catTwoId)' 它对我来说完美无缺。

    您可能遇到 react-router 版本问题,我正在使用 "react-router": "^3.0.0", "react-router-redux": "^4.0.6",

    或者您可以创建https://jsbin.com/https://plnkr.co/ 来模拟您的情况。

    【讨论】:

    • 嗨@veetesh - 请查看我的github项目有这个问题:):github.com/FredM7/react-base
    • @FrederikMoller 您需要在 index.html 中添加 &lt;base href="/" &gt; 或者您需要设置一些 Web 容器来为您的静态文件提供服务 express static files
    • @FrederikMoller 您需要在 index.html 中添加 &lt;base href="/" &gt; 或者您需要设置一些 Web 容器来提供静态文件 express static files。您还需要为您的主要路线添加 path="/" &lt;Route path="/" component={Main}&gt;
    • 谢谢!将 添加到我的 index.html 效果很好!但是你能解释一下为什么我们需要添加它吗?你也有一个网站的参考吗?因为我找不到任何表明我需要添加
    • 不能使用最新的 "react-router-dom": "^4.2.0", "react-router-redux": "5.0.0-alpha.6",
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多