【问题标题】:Symfony and React router, no route foundSymfony 和 React 路由器,找不到路由
【发布时间】:2016-07-03 15:54:34
【问题描述】:

我正在使用 Symfony3,我正在使用 React.js 创建一个捆绑包,并使用自身的 react-router。

问题是当我在 react 中使用路由时,如果我重新加载页面,symfony 路由模块会发送“找不到路由”

我的路由是索引页面的 /admin 和下一页的 /admin/data。

当我加载页面 /admin 一切正常时,我点击链接转到 /admin/data,一切正常,反应动态发送给我,但现在当我刷新 (F5) 页面 /admin/数据,Symfony 拦截它并尝试在其代码中找到路由并重定向到 /404 "No Route Found"。

我在AngularJs上知道,该框架使用ancors Path“localhost://admin/#/data”,这似乎更容易管理,但react-router使用“localhost://admin/data”

我的 symfony 路由:

admin:
  path: /admin
  defaults: { _controller: BiBundle:Admin:default }

我的 React 路由:

import { Router, browserHistory } from "react-router";

<Router history={browserHistory}>
  <Route path="/admin" component={App}>
    <IndexRoute components={{content: DashboardPage}} />
    <Route path="data/list"
      components={{content: DataListPage}} />
    <Route path="*"
      components={{content: _ => <h1>Page not found.</h1>}} />
  </Route>
</Router>

我在 /admin 页面上的链接:

<Link to={'/admin/data/list'}>Data</Link>

我正在考虑修改我的 .htaccess 以将所有 /admin/* 重定向到 /admin,但对于这个问题似乎有点过头了。

我也在使用 Apache2 服务器。

编辑

我已经用 hashHistory 替换了 browserHistory

import { Router, hashHistory } from "react-router";

<Router history={hashHistory}>
  <Route path="/" component={App}>
    <IndexRoute components={{content: DashboardPage}} />
    <Route path="data/list"
      components={{content: DataListPage}} />
    <Route path="*"
      components={{content: _ => <h1>Page not found.</h1>}} />
  </Route>
</Router>

结果改变了我在 AngularJs 中使用的路径(或足够接近),所以现在我有了 /admin#/ 和 /admin#/data/list,所以 symfony 总是捕获 /admin 和 react-router捕捉 #/ 或 #/admin/data

你怎么看?这是好的方法吗?

【问题讨论】:

    标签: javascript php reactjs symfony react-router


    【解决方案1】:

    要使您的 AJAX 路由可以直接从 url 访问(即在浏览器 URL 中键入 /admin/data)而不被重定向到服务器端,您需要使您的基本路由(呈现您的 React 应用程序的 Symfony 路由)采用一个参数:将代表您的 AJAX 路由。

    为此,参数必须allow slashes,例如:

    admin:
        path: /admin/{reactRouting}
        defaults: { _controller: BiBundle:Admin:default, reactRouting: null }
        requirements:
            reactRouting: ".+"
    

    对于更复杂的路由,您应该查看可以帮助您的FOSJsRoutingBundle

    【讨论】:

    • 我将完成答案: admin: path: /admin/{reactRouting} 默认值:{ _controller: BiBundle:Admin:default, reactRouting: null } 要求:reactRouting: ".+" 这是有效的:) HashHistory 似乎更容易管理,因为有亲戚路径,但 browserHistory 似乎更清晰。
    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2018-06-08
    • 2017-09-25
    • 2018-01-26
    • 1970-01-01
    相关资源
    最近更新 更多