react-router中的URL参数问题

问题描述 投票:0回答:2

我一直在尝试使用react-router的Router,Route和Switch组件来跟踪docs

但我完全无法获得URL参数。我可以让所有其他路线工作,但任何涉及/:variable,我似乎无法工作。

从他们的文档中,他们有这样的代码:

import { Switch, Route } from 'react-router'

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

我有这个:

const AppRouter = () => {
    return (
        <Router>
            <div>
                <Header />

                <Switch>
                    <Route exact path="/" component={HomePage} />
                    <Route path="/pricing" component={PricingPage} />
                    <Route path="/contact" component={ContactPage} />
                    <Route path="/signup" component={SignupPage} />
                    <Route path="/login" component={LoginPage} />
                    <Route path="/forgotpassword" component={ForgotPasswordPage} />

                    <Route path="/resetpassword/:token" component={ResetPasswordPage} />

                    <PrivateRoute path="/dashboard" component={DashboardPage} />
                </Switch>
            </div>
        </Router>
    );
};

除了/resetpassword/:token之外,每一个组件/路线都有效,我不能为我的生活找出原因。

当我去http://localhost:8000/resetpassword时,它实际上显示了我的标题组件。

当我去http://localhost:8000/resetpassword/http://localhost:8000/resetpassword/123时,我在控制台中收到这些错误:

GET http://localhost:8000/resetpassword/dist/style.css net::ERR_ABORTED
GET http://localhost:8000/resetpassword/dist/bundle.js 404 (Not Found)

谁能发现我的错误?

Here is a link在我目前的回购中的这个文件,如果这将有所帮助。

谢谢

reactjs react-router
2个回答
1
投票

您使用index.html文件中的相对路径包含脚本和css文件。将其更改为绝对路径,如下所示:

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>React Boilerplate Project</title>
    <!-- use absolute path here with starting / -->
    <link rel="stylesheet" href="/dist/style.css"> </head>

<body>
    <div id="root"></div>
    <!-- use absolute path here with starting / -->
    <script src="/dist/bundle.js"></script> </body>

</html>

0
投票

这个问题的一个原因可能如下

您正在尝试请求服务器获取resetpassword / 123页面,而服务器不知道它是什么。您正在使用react-router并在客户端设置路由。

当您第一次请求页面(可能是localhost 8000)时,您将获得客户端所需的所有javascript文件。从那时起反应路由器到位,如果你点击链接,它会检查客户端是否有任何匹配的路由并呈现适当的组件。即使在你的情况下,如果你直接有一个按钮说“重置密码”,如果你说导航到重置密码路由,它就完全有效。

如果你的应用程序即使在直接命中URL时也需要工作,你应该让服务器也能理解路由。您可以查看URL重写(如果您使用的是IIS)或其他一些机制,您的服务器了解它需要先获取所需的所有javascript,然后导航到您提供的路由。

© www.soinside.com 2019 - 2024. All rights reserved.