React Router:当浏览器的URL更改时,css和js文件的相对路径不正确

时间:2015-12-03 13:25:08

标签: react-router

history.js

var createBrowserHistory = require('history/lib/createBrowserHistory');

var history = createBrowserHistory();

module.exports = history;

routes.js

'use strict';
var React = require('react'),
    ReactRouter = require('react-router'),
    Router = ReactRouter.Router,
    Route = ReactRouter.Route,
    NotFoundRoute = ReactRouter.NotFoundRoute,
    IndexRoute = require('react-router').IndexRoute,
    history = require('./history.js'),
    App = require('./components/app.js'),
    SignupPage = require('./components/signupPage/signupPage.js'),
    SignupSuccessPage = require('./components/signupSuccessPage/signupSuccessPage.js'),
    NotFoundPage = require('./components/notFoundPage/notFoundPage.js');

var routes = (
  <Router history={history}>
    <Route path='/(:languageCode)' component={App} >
      <IndexRoute component={SignupPage} />
      <Route path='/success' component={SignupSuccessPage} />
      <Route path='*' component={NotFoundPage} />
    </Route>
  </Router>
);

module.exports = routes;

的index.html

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>signup page</title>
    <link rel="stylesheet" href="css/bundle.css" />
    <script src="scripts/vendors.bundle.js" type="text/javascript" defer></script>
    <script src="scripts/bundle.js" type="text/javascript" defer></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

正在加载网址:http://localhost:9005/en(按预期工作)
正在加载网址:http://localhost:9005/fr(按预期工作)

但是加载网址:http://localhost:9005/en/success(不按预期工作)

在Google的开发者控制台中,我看到了对文件的请求:

http://localhost:9005/en/css/bundle.css 
http://localhost:9005/en/scripts/vendors.bundle.js 
http://localhost:9005/en/scripts/vendors.vendor.js

但是,如果您查看上面的index.html文件,则网址应为

http://localhost:9005/css/bundle.css 
http://localhost:9005/scripts/vendors.bundle.js 
http://localhost:9005/scripts/vendors.vendor.js

我不确定/ en /是.css和.js文件的网址的一部分。

1 个答案:

答案 0 :(得分:-1)

http://localhost:9005/en/success按预期工作的原因是因为您在开头使用/定义了路径路径,这意味着您要声明绝对路径。如果删除/,您将获得所期望的内容。了解Route Matching的工作原理。

所以你的路线应该是这样的:

var createBrowserHistory = require('history/lib/createBrowserHistory');
var history = createBrowserHistory();

var routes = (
  <Router history={history}>
    <Route path='/(:languageCode)' component={App}>
      <IndexRoute component={SignupPage} />
      <Route path='success' component={SignupSuccessPage} />
      <Route path='*' component={NotFoundPage} />
    </Route>
  </Router>
);