【问题标题】:React Router V4 nested routers are not working on page reloadReact Router V4 嵌套路由器在页面重新加载时不起作用
【发布时间】:2018-12-10 05:58:37
【问题描述】:

我创建了一个新网站http://gk-chart.org/,并使用 react-rotuter-dom 添加了路由。

import {BrowserRouter as Router, Route, Switch} from "react-router-dom";

并将路由器添加为:-

<Switch>
  <Route exact path="/" component={Home}></Route>
  <Route path="/galery" component={Galery}></Route>
</Switch>

对于多种类型图表的嵌套路由,我在 Gallery 组件中添加了这些路由

<Route exact path={this.props.match.path} component={LineChart}></Route>
<Route path={`${this.props.match.path}/line`} component={LineChart}></Route>
<Route path={`${this.props.match.path}/lineChartFill`} component={LineChartFill}></Route>
<Route path={`${this.props.match.path}/lineChartComparision`} component={LineChartComparision}></Route>
<Route path={`${this.props.match.path}/lineChartComparisionFill`} component={LineChartComparisionFill}></Route>

路由器在点击链接时工作正常,但是当我尝试重新加载页面时,页面没有再次加载。

在图库页面http://gk-chart.org/galery 中存在多个嵌套路由,当我单击这些路由时,它们会正确加载,但是当我重新加载页面时,它不会加载。 请帮我解决这个问题。

【问题讨论】:

    标签: javascript reactjs routing react-router-dom


    【解决方案1】:

    服务器不知道您的客户端路由。您的构建过程可能会生成一个引用您的资源的 index.html。该 index.html 被放置在/galery/index.html。单击刷新时,服务器会在 /galery/line/index.html 处查找文件,但未找到。

    这是一个常见问题。为了解决这个问题,许多人告诉服务器提供/galery/index.html,而不是使用某种规则。这取决于您的文件是如何托管的。 react 应用程序将在客户端启动,查看略有不同的路由,并正确渲染路由。

    【讨论】:

    • 谢谢@Leland Barton,我只有一个 index.html,我试图从那里加载我的 bundle.js,但是当我加载页面时,它再次在 / 中搜索 index.html galey/index.html ,但我没有那种名为 /galey 的文件夹,所以我不明白如何解决这个问题。有什么技巧可以为此使用路由器。
    • 这是您如何托管 React 应用程序的问题。您需要查找您的服务器并查看如何重定向到该文件。
    【解决方案2】:

    在漫游到这么多网站以获得这个答案后,我终于知道 react 有两种类型的路由器:-

    1. HashRouter 用于静态路由网站,也可以称为自驱动路由。

    2. BrowserRouter 用于服务器支持的路由。

    我在我的网站上使用了错误的 BrowserRouter,因为我没有任何类型的服务器支持(节点、python 等...) 所以我必须使用HashRouter

    import {HashRouter as Router, Route, Switch} from "react-router-dom";
    

    修复http://gkchart.com/使用Hashrouter的问题。

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2021-03-28
      • 1970-01-01
      • 2017-11-11
      • 2017-08-28
      • 2017-09-13
      • 2017-12-15
      • 2019-01-07
      相关资源
      最近更新 更多