react-router-dom 直接访问子路径
react-router-dom direct access to child path
我的主要组件中的主要路线是这样设置的
<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 I see the right page (the UsersPage component) and when I click on a user it transfer to http://localhost:3000/users/someUserId 一样访问它时(我使用 <Link>
来访问它)并且它工作得很好..但是当我刷新或尝试直接丰富到特定的用户页面我得到一个试图加载 http://localhost:3000/users/main.js
的空白页面(我不知道为什么它试图加载这个文件)我猜这是来自 react-router-dom 我试图 google 它,但我没有找到任何相关的东西......不能把我的手放在我错过的东西上。
谢谢。
好的,您的页面是空白的,因为它无法下载初始化您的 React 应用程序的 main.js
文件。
对应于您的开发服务器输出-[=30=]-路径(默认为/
)您应该可以使用以下URL下载main.js
: http://localhost:3000/main.js
,但你有 http://localhost:3000/users/main.js
。这是因为您在 html 文件中为 <script>
指定了 src='main.js'
,这是一个相对路径。服务器采用当前 URL 路径 (http://localhost:3000/users/
) 并将其与 main.js
连接起来。我们有 http://localhost:3000/users/main.js
.
您只需要使用绝对路径设置您的 <script>
src
属性:
src="/main.js"
.
我的主要组件中的主要路线是这样设置的
<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 I see the right page (the UsersPage component) and when I click on a user it transfer to http://localhost:3000/users/someUserId 一样访问它时(我使用 <Link>
来访问它)并且它工作得很好..但是当我刷新或尝试直接丰富到特定的用户页面我得到一个试图加载 http://localhost:3000/users/main.js
的空白页面(我不知道为什么它试图加载这个文件)我猜这是来自 react-router-dom 我试图 google 它,但我没有找到任何相关的东西......不能把我的手放在我错过的东西上。
谢谢。
好的,您的页面是空白的,因为它无法下载初始化您的 React 应用程序的 main.js
文件。
对应于您的开发服务器输出-[=30=]-路径(默认为/
)您应该可以使用以下URL下载main.js
: http://localhost:3000/main.js
,但你有 http://localhost:3000/users/main.js
。这是因为您在 html 文件中为 <script>
指定了 src='main.js'
,这是一个相对路径。服务器采用当前 URL 路径 (http://localhost:3000/users/
) 并将其与 main.js
连接起来。我们有 http://localhost:3000/users/main.js
.
您只需要使用绝对路径设置您的 <script>
src
属性:
src="/main.js"
.