【问题标题】:How to redirect to a sub directory in react using react router?如何使用反应路由器重定向到反应中的子目录?
【发布时间】:2020-12-05 20:07:51
【问题描述】:

我在根域假设 domain.com 安装了一个 react 应用程序,并且我已经在名为 domain.com/blog 的子目录中安装了 Wordpress。如果我添加像 <Route exact path="/blog" /> 这样的空路线,我会得到一个空白页。 有没有办法访问 react 组件之外的子目录中的 .php 或 .html 文件?

请参考下面的路由代码

    <BrowserRouter>
          <Switch>
            <Switch>
              <Route exact path="/" render={(props) => <Index {...props} />} />
    
              {/*route added since /blog redirects to / because of 404 condition at the bottom */}
              {/* <Route exact path="/blog" /> */}
    
              {/*404 redirection for other URLs */}
              <Redirect to="/" />
              <Redirect from="/" to="/" />
            </Switch>
          </Switch>
        </BrowserRouter>

由于下面添加的重定向,如果我不为 /blog 提供路由,它会重定向到根 '/' URL(这是 404 页面未找到条件)。

【问题讨论】:

    标签: php html reactjs wordpress react-router


    【解决方案1】:

    Route 仅用于 react 的内部路由。如果你想路由一些其他平台的url,你需要使用anchor(a tag)

    您可以在这里阅读更多内容this

    <a href="https://example.com/blog">Go to Blog</a>
    

    更新:

    <BrowserRouter>
          <Switch>
            <Switch>
              <Route exact path="/" render={(props) => <Index {...props} />} />
    
              <Route path="*" render={props => <NotFound />}
            </Switch>
          </Switch>
        </BrowserRouter>
    

    【讨论】:

    • 我明白你的意思,但是我必须为博客 url 提供一个路由,因为我添加了一个 404 重定向,这样所有其他路由都会被重定向到一个 404 组件。有没有办法获取 404 路由并将自定义路由定向到子目录
    • Route 只需要 react 的内部路由。您不需要为其他网址添加任何路由。对于其他网址,您需要添加标签而不是链接。链接只会用于 react 的内部 url。
    • 我明白了!但我正在使用 404 重定向路由 &lt;Redirect to="/" /&gt; ,因此如果我写 domain.com/blog 它会被重定向到主页。仅当我专门为博客提供路线时,这才会停止。有没有其他方法可以将其重定向到域并实现 404 重定向?
    • 请分享您的代码。还有另一种可能。在新标签中打开博客,您的反应站点将重定向到主页。
    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多