react-router-dom 直接访问子路径

gre*_*reW 5 reactjs react-router react-router-dom

我在我的主要组件中设置了我的主要路线

<Main>
    <Switch>
        <Route exact path="/login" component={ LoginPage }/>
        <PrivateRoute path="/" component={ PrivatePages }/>
    </Switch>
</Main>
Run Code Online (Sandbox Code Playgroud)

和里面PrivatePages的路线是这样设置的

<div>
    <Switch>
        <Route exact path="/users/:id" component={ UsersPage }/>
    </Switch>
</div>
Run Code Online (Sandbox Code Playgroud)

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

谢谢。

GPr*_*ost 4

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

对应于您的开发服务器输出公共路径(/默认情况下),您应该能够main.js使用以下 URL 下载:http://localhost:3000/main.js,但是您有http://localhost:3000/users/main.js. 这是因为您在 html 文件中指定了src='main.js'for ,这是一个相对路径。<script>服务器获取当前 URL 路径 ( http://localhost:3000/users/) 并将其与main.js. 我们有http://localhost:3000/users/main.js

您只需<script> src使用绝对路径设置您的属性: src="/main.js"