我正在使用React-router,当我点击链接按钮时,它工作得很好,但当我刷新我的网页时,它没有加载我想要的东西。

例如,我在localhost/joblist和一切都很好,因为我到达这里按下一个链接。但如果我刷新网页,我会得到:

Cannot GET /joblist

默认情况下,它不是这样工作的。最初我有我的URL localhost/#/和localhost/#/joblist,他们工作得很好。但我不喜欢这种类型的URL,所以试图删除#,我写道:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

这个问题不会发生在localhost/,这个总是返回我想要的。

这个应用程序是单页的,所以/joblist不需要向任何服务器询问任何事情。

我的整个路由器。

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

当前回答

路由器可以用两种不同的方式调用,这取决于导航是发生在客户端还是服务器上。您已经将其配置为客户端操作。关键参数是run方法的第二个参数,即location。

当你使用React Router Link组件时,它会阻塞浏览器导航并调用transitionTo来做客户端导航。您正在使用HistoryLocation,因此它使用HTML5历史API通过在地址栏中模拟新URL来完成导航的错觉。如果您使用的是较旧的浏览器,这将不起作用。您将需要使用HashLocation组件。

When you hit refresh, you bypass all of the React and React Router code. The server gets the request for /joblist and it must return something. On the server you need to pass the path that was requested to the run method in order for it to render the correct view. You can use the same route map, but you'll probably need a different call to Router.run. As Charles points out, you can use URL rewriting to handle this. Another option is to use a Node.js server to handle all requests and pass the path value as the location argument.

例如,在Express.js中,它看起来是这样的:

var app = express();

app.get('*', function (req, res) { // This wildcard method handles all requests

    Router.run(routes, req.path, function (Handler, state) {
        var element = React.createElement(Handler);
        var html = React.renderToString(element);
        res.render('main', { content: html });
    });
});

请注意,正在传递请求路径以运行。为此,需要有一个服务器端视图引擎,可以将呈现的HTML传递给该引擎。在使用renderToString和在服务器上运行React时,还有许多其他注意事项。一旦页面在服务器上呈现,当你的应用程序在客户端加载时,它将再次呈现,并根据需要更新服务器端呈现的HTML。

其他回答

因为我使用ASP。NET Core,类似这样的东西帮助了我:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var url = Request.Path + Request.QueryString;
        return App(url);
    }

    [Route("App")]
    public IActionResult App(string url)
    {
        return View("/wwwroot/app/build/index.html");
    }

}

基本上是在ASP上。NET MVC端,所有不匹配的路由都将落在startup.cs中指定的Home/Index中。在索引中,可以获取原始请求URL并将其传递到任何需要的地方。

文件startup.cs

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

这里的答案都非常有用。配置我的Webpack服务器以期望路由对我有效。

devServer: {
   historyApiFallback: true,
   contentBase: './',
   hot: true
},

historyApiFallback为我修复了这个问题。现在路由工作正确,我可以刷新页面或直接输入URL。没有必要担心Node.js服务器上的变通方法。这个答案显然只适用于使用Webpack的情况。

查看我对React-router 2.0 browserHistory在刷新时不工作的回答,了解为什么需要刷新的更详细原因。

这里有一个简单、清晰和更好的解决方案。如果你使用网络服务器,它就可以工作。

每个web服务器都有能力在出现HTTP 404时将用户重定向到错误页面。要解决此问题,需要将用户重定向到索引页。

如果您使用Java基础服务器(Tomcat或任何Java应用程序服务器),解决方案可能如下:

web . xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!-- WELCOME FILE LIST -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- ERROR PAGES DEFINITION -->
    <error-page>
        <error-code>404</error-code>
        <location>/index.jsp</location>
    </error-page>

</web-app>

例子:

得到http://example.com/about web服务器抛出HTTP 404,因为此页面在服务器端不存在 错误页面配置通知服务器将index.jsp页面发送回用户 那么JavaScript将在客户端完成剩下的工作,因为客户端的URL仍然是http://example.com/about。

就是这样。不再需要魔法:)

对于React Router V4用户:

如果您试图通过其他答案中提到的哈希历史技术来解决这个问题,请注意

<Router history={hashHistory} >

在V4中不能工作。请改用HashRouter:

import { HashRouter } from 'react-router-dom'

<HashRouter>
  <App/>
</HashRouter>

参考:HashRouter

如果你通过AWS Static S3 hosting和CloudFront托管React应用程序

这个问题由CloudFront以403 Access Denied消息响应,因为它期望/some/other/路径存在于我的S3文件夹中,但该路径只存在于React路由器的内部路由中。

解决方案是设置一个分发错误页面规则。转到CloudFront设置并选择您的发行版。接下来,进入“错误页面”选项卡。单击“创建自定义错误响应”,并添加403条目,因为这是我们获得的错误状态代码。

将响应页路径设置为/index.html,状态代码设置为200。

最终的结果让我惊讶于它的简单。索引页被提供,但URL保存在浏览器中,因此一旦React应用程序加载,它就会检测URL路径并导航到所需的路由。

错误页403规则