我正在使用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);
});

当前回答

将此添加到webpack.config.js:

devServer: {
    historyApiFallback: true
}

其他回答

当我在Electron中使用React作为前端,使用React -router-dom作为路由时,我就遇到了这个问题。

我用HashRouter替换了BrowserRouter,这是固定的。

这里有一个简单的例子:

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

假设你有以下Home route定义:

<Route exact path="/" render={routeProps => (
   <Home routeProps={routeProps}/>
)}/>

{/* Optional catch-all router */}
<Route render={routeProps => (
       <div><h4>404 not found</h4></div>
)}/>

在你的Home组件中,你可以在ComponentWillMount事件中拦截请求,

const searchPath = this.props.routeProps.location.search;

if (searchPath){
    this.props.routeProps.history.push("/" + searchPath.replace("?",""));
}
else{
    /*.... originally Home event */
}

现在,不是在URL处调用/joblist,而是请求/?<Home>组件将自动将请求重定向到/joblist(注意路径中有额外的问号)。

在我的情况下,URL没有加载时,我使用一个参数。

作为权宜之计,我补充道 <基地href = " < yourdomain / IP > " > < /基础> 在build文件夹中index.html文件的<title>标签下。

这刚好解决了我的问题。

如果您在谷歌桶上运行它,简单的解决方案是考虑'index.html'为错误(404 not found)页面。

这样做:

在桶的列表中,找到您创建的桶。 单击桶关联的桶溢出菜单(…),选择“编辑网站配置”。 在网站配置对话框中,将主页也指定为错误页面。

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

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

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

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