【发布时间】:2019-07-25 22:09:29
【问题描述】:
我正在使用 create-react-app 和 react-router 创建一个反应应用程序。 我想获取我的 react 应用程序的根 URL 路径,因为它可以在不同的位置提供:
- 生产中:example.com/interface/
- 在本地:localhost/
不同页面的链接不受这种差异的影响,因为 react-router 根据 react 根路径处理 to-location。
实际上,我的图像存储在公共路径中,因此,我可以在基本位置访问它:/<page>
<img src={images/example.png}>
但如果我在子页面中,或者只是 URL 以“/”结尾,例如 /<page>/
<img src={images/example.png}>
无法正常工作,因为浏览器在 /<page>/images/example.png 而不是 /images/example.png 搜索图像。
此外,如果我将图像 src 设置为 /images/example.png 它仅适用于 localhost 但不适用于生产,因为在生产中,浏览器会在 example.com/images/example.png 而不是 example.com/interface/images/example.png 搜索图像
这就是为什么我需要获取反应根 URL 路径。例如,它允许我在 localhost 中获取“/”,在生产中获取“/interface/”
感谢您的帮助
【问题讨论】:
-
在您的
<head>部分尝试使用<base href="http://localhost/" />。
标签: reactjs url path react-router location