javascript - 与自定义路由 react (在 Symfony 后端)

标签 javascript reactjs symfony react-router

刚开始新的 React 项目(还是 React 的初学者),我必须处理有关路由的新问题。

网站基于 Symfony 后端,前端使用 React。启动页面时,我必须转到需要 slug 的 URL,它由 Symfony 路由控制,没关系:

//domain.com/slug

但是后来我有了 React 应用程序,其中所有内容都发生在单个页面上。在这个单一页面上,我有一个容器,我必须在其中根据用户操作(例如简单的单击链接)切换组件。不是整个页面都在重新加载,只有组件容器部分。这很简单,因为 MainPage 组件的这一部分(根):

<header>some header</header>
<div id="content-wrapper">
    <div class="switch-components-inside">
        <ComponentsWrapper page={this.state.subPage} />
    </div>
</div>
<footer>footer!</footer>

老实说我很困惑,因为我不知道如何使用 react-router 来构建这样的结构。也许我应该自己修改网址?我希望能够使用这样的 URL(当然可以在 slug 之后使用哈希),但是所有这些都应该指向同一个组件(MainPage)并且只有网站的一部分应该加载不同的组件。

//domain.com/slug#/news
//domain.com/slug#/news/some-news
//domain.com/slug#/authors
//domain.com/slug#/authors/some-author

感谢您的帮助。

最佳答案

使用 react-router HashRouter 用于基于哈希的路由。

A <Router> that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

IMPORTANT NOTE: Hash history does not support location.key or location.state. In previous versions we attempted to shim the behavior but there were edge-cases we couldn't solve. Any code or plugin that needs this behavior won't work. As this technique is only intended to support legacy browsers, we encourage you to configure your server to work with instead.

所以在你的情况下你可能有:

const App = () => {
  return (
    <HashRouter>
      <div>
        <header>some header</header>
        <div id="content-wrapper">
          <Switch>
            <Route path="/news" component={NewsComponent}/>
            <Route path="/authors" component={AuthorsComponent}/>
          </Switch>
        </div>
        <footer>footer!</footer>
      </div>
    </HashRouter>
  )
};

不过,根据重要说明,最好将后端配置为忽略嵌套在 //domain.com/slug 下的路由。而是使用 <BrowserRouter basename="/slug">

关于javascript - 与自定义路由 react (在 Symfony 后端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47349025/

相关文章:

javascript - 我想在astro js中导入bootstrap js和jquery js文件

javascript - 当元素溢出时如何增加元素的高度

reactjs - 有没有一种方法可以在 React 应用程序中使用样式组件,而无需重命名所有现有组件?

sql-server - Symfony2 + Doctrine2 + SQL Server - 事务支持

symfony - 如何在symfony2中一键提交多个相同类型的表单

javascript - 如何使用 JSDoc 记录 useState Hook ?

javascript - ui-router 通过服务将 URL 查询参数传递给 Controller ​​ - $stateParams 值 'undefined'

javascript - 为什么我使用 JavaScript 的点导航不起作用。 (不会跳转到页面上的部分)

javascript - 如何在异步的 React 功能组件中使用 useState

php - 无法使用 Doctrine 创建 postgres 数据库