gpt4 book ai didi

javascript - react 路由器 `browserHistory` : Do I have to render on server?

转载 作者:行者123 更新时间:2023-11-30 08:27:12 26 4
gpt4 key购买 nike

我是 React 的新手,刚开始学习路由的工作原理。 hashHistory (/#/paths/like/this) 效果很好,但是 browserHistory (/paths/like/this ) 看起来好多了。显然,当我重新打开 URL 时,browserHistory 路径无法立即使用,因为浏览器请求的 /path/on/server 不存在。

问题是:我是否必须使用服务器端渲染(所谓的同构渲染)才能使用/nice/paths并让用户直接打开页面,或者能够 Ctrl+R 页面并保持原样,或者可以选择只保持 client-side 渲染?

谢谢。

最佳答案

不,您可以轻松地使用客户端 呈现并允许用户使用像nice/paths/ 这样的路径。

由于这些路由只是 React 的便利,服务器上不存在,因此直接访问它们会抛出错误,因为页面根本不存在。要解决这个问题,您应该将所有路由指向服务器中的 index.html(应用程序的入口点),然后让 React 接管该路径。

在 Express 中,它会像这样完成:

app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html')
})

对于 Apache 服务器,这将是 .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>

对于其他服务器端语言,它们有自己的方法,指向 index.html 的方法基本上适用于所有 SPA 框架,例如 Angular 等,因为逻辑是相同的。

关于javascript - react 路由器 `browserHistory` : Do I have to render on server?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43624559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com