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

当前回答

如果你在后端使用Express.js或其他框架,你可以添加如下所示的类似配置,并在配置中查看Webpack公共路径。如果你正在使用BrowserRouter,即使在重载时它也应该工作得很好。

expressApp.get('/*', (request, response) => {
    response.sendFile(path.join(__dirname, '../public/index.html'));
});

其他回答

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

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

这刚好解决了我的问题。

我喜欢这种处理方式。尝试添加: yourSPAPageRoute/*在服务器端消除这个问题。

我采用了这种方法,因为即使是原生HTML5 History API也不支持页面刷新时的正确重定向(据我所知)。

注意:选定的答案已经解决了这个问题,但我试图更具体。

表达的路线

产品堆栈:React, React Router v4, BrowswerRouter, Express.js, Nginx

User BrowserRouter for pretty URLs File app.js import { BrowserRouter as Router } from 'react-router-dom' const App = () { render() { return ( <Router> // Your routes here </Router> ) } } Add index.html to all unknown requests by using /* File server.js app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) { if (err) { res.status(500).send(err) } }) }) bundle Webpack with webpack -p run nodemon server.js or node server.js

你可能想让nginx在服务器块中处理这个问题,忽略第2步:

location / {
    try_files $uri /index.html;
}

下面是我发现的一个前端解决方案,不需要修改服务器上的任何内容。

假设你的网站是mysite.com,你有一个到mysite.com/about的React Route。 在index.js中,你可以挂载你的顶级组件,你可以像这样放另一个Router:

ReactDOM.render(
<Router>
    <div>
        <Route exact path="/" component={Home} />
        <Route exact path="/about"
            render={(props) => <Home {...props} refreshRout={"/about"}/>}
        />
    </div>
</Router>,

我假设原始路由器位于虚拟DOM的顶级组件之下。如果你正在使用Django,你还必须在你的。url中捕获url:

urlpatterns = [
       path('about/', views.index),
]

不过,这将取决于您使用的后端。请求mysite/about会让你进入index.js(在那里你挂载顶级组件),在那里你可以使用Route的渲染道具,而不是组件道具,并将'/about'作为道具传递给Home组件,在这个例子中。

在Home中,在componentDidMount()或useEffect()钩子中,执行以下操作:

useEffect() {
   //check that this.props.refreshRoute actually exists before executing the
   //following line
   this.props.history.replace(this.props.refreshRoute);
}

我假设你的Home组件是这样渲染的:

<Router>
   <Route exact path="/" component={SomeComponent} />
   <Route path="/about" component={AboutComponent} />
</Router>

关于如何在路由中向组件传递道具,请参考(将道具传递给React路由器渲染的组件)。

如果您正在使用“create-react-app”命令,

生成一个React应用程序,然后生成包。json文件需要有一个更改,以在浏览器中正常运行的产品构建React SPA。打开文件包。Json,并添加以下代码段,

"start": "webpack-dev-server --inline --content-base . --history-api-fallback"

这里最重要的部分是“——history- API -fallback”,用于启用历史API回调。

如果使用Spring或任何其他后端API,有时会出现404错误。因此,在这种情况下,您需要在后端有一个控制器,将任何请求(您想要的)转发给index.html文件,由react-router处理。下面演示了一个使用Spring编写的示例控制器。

@Controller
public class ForwardingController {
    @RequestMapping("/<any end point name>/{path:[^\\.]+}/**")
    public String forward(HttpServletRequest httpServletRequest) {
        return "forward:/";
    }
}

例如,如果我们取一个后端API REST端点为“abc”(http://localhost:8080/abc/**),任何到达该端点的请求都将重定向到React应用程序(index.html文件),然后React -router将处理它。