React嵌套路由无法在刷新时加载

Uco*_*dia 7 routing http-status-code-404 reactjs react-router webpack-dev-server

我有一个React应用程序,其导航功能由react-router我在开发中运行webpack-dev-server并启用了历史回退选项.这是我在我的定义中的路线index.js

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRedirect to="/intro" />
      <Route path="/intro" component={Intro} />
      <Route path="/device" component={Device} />
      <Route path="/clothing" component={Clothing} />
      <Route path="/build" component={Build}>
        <IndexRedirect to="/build/pattern" />
        <Route path="/build/pattern" component={Pattern} />
        <Route path="/build/layout" component={Layout} />
        <Route path="/build/color" component={Color} />
      </Route>
      <Route path="/capture" component={Capture} />
      <Route path="/review" component={Review} />
    </Route>
  </Router>
), document.getElementById('app'))
Run Code Online (Sandbox Code Playgroud)

当我浏览链接时,一切正常,我可以看到嵌套的路由组件嵌套在其父路由组件中,如预期的那样.例如,当我导航到/build/color我可以看到我的App组件嵌套嵌套Build组件的Color组件.

它失败的地方是我尝试在嵌套路径中点击刷新按钮.React完全无法加载,我收到以下错误

获取http:// localhost:8080/build/app.js 404(未找到)

在我的应用程序中确实没有这样的文件,但我仍然感到困惑,为什么它会自动查找此文件而不是从根重新加载路由.请注意,在页面上点击刷新/device会没有问题.

如果您需要有关我的设置的更多详细信息,请告诉我.谢谢!


解:

我的webpack设置实际上是使用HtmlWebpackPlugin注入我的应用程序包的路径,如下所示

<script src="app.js" type="text/javascript"></script>

我需要做的就是配置我的webpack公共路径,publicPath: '/'以便按如下方式注入bundle

<script src="/app.js" type="text/javascript"></script>

nib*_*iba 24

它不起作用,因为它无法加载您的JavaScript包.我猜这个问题与你在HTML中的脚本标记中的路径有关.可能你已经指定了app.js的路径,开头就像这个一样 <script src="./app.js"></script>,如果是这样的话,请删除dot并检查问题是否仍然存在<script src="/app.js"></script>

让我们来说明./app.js和之间的区别/app.js

案例1.您正在使用/或等的第一级路线加载页面/intro

  • ./app.js:HTML尝试从中加载脚本 http://address/app.js
  • /app.js:HTML尝试从中加载脚本 http://address/app.js

没有不同

案例2.您正在使用第二级路由加载页面 /build/pattern

  • ./app.js:HTML尝试从中加载脚本http://address/build/app.js- 不存在
  • /app.js:HTML尝试从中加载脚本http://address/app.js- 确定

  • 如果您使用`HTML Webpack Plugin`生成HTML,则需要设置`webpackConfig.output.publicPath ='/'` (6认同)

Z_K*_*Z_K 9

@niba 的回答完美地解决了我的问题。我一直遇到的问题是,当我<Route/>在已经由 a 呈现的组件中嵌套一个元素<Route/>时,当我尝试转到子路由 url 时,它将无法加载脚本 bundle.js。在 webpackConfig.json 中添加以下内容后,一切恢复正常。

module.exports = {
    ...
    output: {
        path: path.resolve('dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 我只是缺少 `publicPath: '/',` (2认同)