如何使用react-router在浏览器中停止/#/?

reactjs React.js

番长神无

2020-03-12

/#/在使用react-router时,有什么方法可以防止在浏览器的地址栏中显示?那就是ReactJS。即,单击链接以转到新路线将显示localhost:3000/#/localhost:3000/#/about取决于路线。

第1043篇《如何使用react-router在浏览器中停止/#/?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
蛋蛋阿飞小小 2020.03.12

如果不需要支持IE8,则可以使用“浏览器历史记录”,然后使用react-router window.pushState代替设置哈希。

具体如何执行取决于您使用的React Router版本:

LJinJin 2020.03.12

您实际上可以使用.htaccess来完成此操作。浏览器通常需要查询字符串定界符?#确定查询字符串在何处开始以及目录路径在何处结束。我们想要的最终结果是www.mysite.com/dir 因此,我们需要在Web服务器搜索它认为我们想要的目录之前捕获问题/dir因此,我们将.htaccess文件放置在项目的根目录中。

    # Setting up apache options
    AddDefaultCharset utf-8
    Options +FollowSymlinks -MultiViews -Indexes
    RewriteEngine on

    # Setting up apache options (Godaddy specific)
    #DirectoryIndex index.php
    #RewriteBase /


    # Defining the rewrite rules
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{SCRIPT_FILENAME} !-f

    RewriteRule ^.*$ ./index.html

然后使用window.location.pathname获取查询参数

然后,您可以根据需要避免使用react路由,并且也可以仅操纵url和浏览器历史记录。希望这可以帮助某人...

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

对于当前版本0.11及更高版本,您需要添加Router.HistoryLocationRouter.run()<Routes>现在已弃用。有关 0.12.x HistoryLocation的实现,请参阅《升级指南》

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android