【问题标题】:React Router v5: 404 when use url directly or refresh page on route different from "/"React Router v5: 404 当直接使用 url 或在不同于“/”的路由上刷新页面时
【发布时间】:2024-05-18 23:45:02
【问题描述】:

我使用 React Router v5:

"react-router-dom": "^5.2.0",
"react-router-hash-link": "^2.4.3",

我需要允许页面刷新并允许使用直接 url。所以,就目前而言,当我尝试使用“/”以外的路由刷新页面时,我得到了 404。此外,当我尝试在浏览器地址栏中使用直接链接时,我也得到了 404。我如何尝试解决这个问题:

  1. 尝试使用 HashRouter 而不是 BrowserRouter(不走运)

  2. 由于我在 apache 网络服务器上托管我的应用程序,因此我添加了带有以下规则的 .htaccess:

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

没有帮助。

我要达到的目的:比如我在/test/route路由上,我想在刷新页面时加载与该路由相关的组件,或者尝试直接在localhost/test/route url 的另一个标签。

你能帮我实现这个吗?

附:我还在 index.html 中添加了<base href="/" />。但这也无济于事。

更新:这是我的路线的样子:

<Switch>
  <Route exact path="/">
    <MainPage />
  </Route>
  <Route exact path="/topic">
    <TopicPage />
  </Route>
  <Route exact path="/about">
    <AboutPage />
  </Route>
  ...
</Switch>

【问题讨论】:

  • 感谢您的详细帖子。您能否告诉我们您正在访问的 URL(示例 url)以及它们应该从后端的哪个文件中获取?
  • @RavinderSingh13 感谢您的回复!我没有后台。我只是用 webpack 运行我的应用程序:npm run build/start。在我的应用程序中,所有路由都有相对路径 url:/about、/feedback 等等。所以,当我刚刚启动应用程序时,默认情况下路由等于“/”(localhost)。当我尝试转到另一个 url,例如“localhost/about”然后我刷新页面时,我将再次被重定向到“/”。直接链接也一样。应用程序始终将其重定向到“/”。
  • @RavinderSingh13 我在上面的问题中添加了我的路线配置。

标签: reactjs .htaccess react-router


【解决方案1】:

好吧,我终于解决了这个问题。首先,我将 BrowserRouter 替换为 HashRouter,正如它在 * 上的另一个答案中所建议的那样。

但我仍然遇到重定向到“/”的情况。因此,我添加了带有超时的 useEffect 以重定向到所需的路由:

const history = useHistory();
const location = useLocation();

useEffect(() => {
    setTimeout(() => {
        history.push(location.pathname);
    }, 100);
}, []);

这对我有用。它在刷新所选路线上的页面时起作用。这在浏览器地址栏中直接使用 url 时有效。

附:此解决方案无需使用 .htaccess。

更新:我添加了一些代码以使重定向与哈希一起工作。

useEffect(() => {
    setTimeout(() => {
        history.push(location.pathname);
        const hash = location.hash.trim();
        if (hash) {
            window.location.href = `#${location.pathname}${location.hash}`;

            const id = hash.replace("#", "");
            const element = document.getElementById(id);
            if (element) {
                // in case if scroll has offset (20 is offset)
                const elementPosition = element.offsetTop - 20;
                window.scroll({
                    top: elementPosition,
                    left: 0,
                    behavior: "smooth"
                });
            }
        }
    }, 100);
}, []);

【讨论】: