【问题标题】:react-router-dom direct access to child pathreact-router-dom 直接访问子路径
【发布时间】:2018-03-01 18:27:39
【问题描述】:

我的主要组件集中有我的主要路线

<Main>
    <Switch>
        <Route exact path="/login" component={ LoginPage }/>
        <PrivateRoute path="/" component={ PrivatePages }/>
    </Switch>
</Main>

PrivatePages 内部,路由是这样设置的

<div>
    <Switch>
        <Route exact path="/users/:id" component={ UsersPage }/>
    </Switch>
</div>

当我像http://localhost:3000/users 一样访问它时,我看到了正确的页面(UsersPage 组件),当我点击一个用户时,它会转移到http://localhost:3000/users/someUserId(我正在使用&lt;Link&gt; 进行此操作)并且它工作得很好..但是当我刷新或尝试直接丰富到特定用户的页面时,我得到一个尝试加载http://localhost:3000/users/main.js 的空白页面(我不知道为什么它试图加载这个文件)我猜这是来自反应的东西-router-dom 我试图用谷歌搜索它,但我没有找到任何相关的东西......我不能把我的手指放在我完全错过的东西上。

谢谢。

【问题讨论】:

  • 我猜你正在使用 browserRouter,也许这个答案会帮助你解决它stackoverflow.com/questions/40332753/…
  • @ShubhamKhatri 感谢您的回复,我确实将 webpack 配置中的 historyApiFallback 设置为 true。但我认为这与他无法加载页面不同,对我来说,它旨在加载 /users/main.js,如果加载 index.js 可能会很好
  • 所以它会将您重定向到http://localhost:3000/users/main.js?如果你使用webpack-dev-server,请显示你的 webpack 配置。
  • @GProst,当我试图直接丰富特定用户http://localhost:3000/users/someUserId 时,它根本不会重定向它显示一个尝试加载http://localhost:3000/users/main.js 的空白页面这是@987654337 中的开发配置@pastebin.com/RWAb2yCy
  • 谢谢,您能否也显示http://localhost:3000/users/someUserId 的准确服务器响应?另外,控制台有错误吗?

标签: reactjs react-router react-router-dom


【解决方案1】:

好的,你的页面是空白的,因为它无法下载你的 main.js 文件来初始化你的 React 应用程序。

对应于您的开发服务器 output-public-path(默认为 /),您应该能够使用以下 URL 下载 main.jshttp://localhost:3000/main.js,但您有 http://localhost:3000/users/main.js。这是因为您在 html 文件中为 &lt;script&gt; 指定了 src='main.js',这是一个相对路径。服务器获取当前 URL 路径 (http://localhost:3000/users/) 并将其与 main.js 连接。我们有http://localhost:3000/users/main.js

您只需使用绝对路径设置&lt;script&gt; src 属性: src="/main.js".

【讨论】:

猜你喜欢
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 2021-12-28
  • 2017-12-16
  • 2020-05-03
  • 1970-01-01
相关资源
最近更新 更多