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

当前回答

我用React路由器(Apache)为我的SPA找到了解决方案。只要在文件.htaccess中添加这个:

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

来源:Apache的React路由器配置

其他回答

如果你正在使用Create React App:

你可以在Create React App页面上找到许多主要托管平台的解决方案。例如,我使用React Router v4和Netlify作为前端代码。它只需要在我的公用文件夹中添加一个文件(“_redirects”),并在该文件中添加一行代码:

/*  /index.html  200

现在,当进入浏览器或有人点击刷新时,我的网站正确地呈现mysite.com/pricing这样的路径。

这可以解决你的问题。

在生产模式下的React应用程序中,我也遇到了同样的问题。这里有两个解决这个问题的方法。

解决方案1。将路由历史更改为“hashHistory”,而不是browserHistory

<Router history={hashHistory} >
   <Route path="/home" component={Home} />
   <Route path="/aboutus" component={AboutUs} />
</Router>

现在使用命令构建应用程序

sudo npm run build

然后将构建文件夹放在var/www/文件夹中。现在,在每个URL中添加#标签,应用程序就可以正常工作了。就像

localhost/#/home
localhost/#/aboutus

解决方案2:没有#标签使用browserHistory,

在路由器中设置你的history = {browserHistory}。现在使用sudo npm run build构建它。

您需要创建“conf”文件来解决404 not found页面。conf文件应该是这样的。

打开终端,输入以下命令

cd /etc/apache2/sites-available
ls
nano sample.conf

在其中添加以下内容

<VirtualHost *:80>
    ServerAdmin admin@0.0.0.0
    ServerName 0.0.0.0
    ServerAlias 0.0.0.0
    DocumentRoot /var/www/html/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory "/var/www/html/">
            Options Indexes FollowSymLinks
            AllowOverride all
            Require all granted
    </Directory>
</VirtualHost>

现在您需要使用以下命令启用sample.conf文件:

cd /etc/apache2/sites-available
sudo a2ensite sample.conf

然后,它将要求您重新加载Apache服务器,使用

sudo service apache2 reload or restart

然后打开您的localhost/build文件夹,并添加包含以下内容的.htaccess文件。

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ / [L,QSA]

现在应用程序运行正常。

注意:0.0.0.0 IP地址修改为本地IP地址。

因为我使用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" });
});

使用useEffect读取URL并应用您想要的更改。


例如,一个页面有一个按钮,打开一个滑块。单击按钮时,将向URL中添加滑块的查询参数,并打开滑块。

问题-在刷新页面时打开滑块,加载的页面不显示打开的滑块,即使查询参数存在。

解决方案:添加一个useEffect,读取“slider”查询参数,并运行按钮处理程序。为滑块查询参数添加一个状态变量,并将其包含在useEffect的依赖数组中。

你不需要担心后端请求,假设在滑块组件中有一个。

修复在刷新或直接调用URL时“不能GET /URL”的错误。

配置你的webpack.config.js,以期望给定的链接像这样的路由。

module.exports = {
  entry: './app/index.js',
  output: {
       path: path.join(__dirname, '/bundle'),
       filename: 'index_bundle.js',
       publicPath: '/'
  },