如何在React和symfony项目中管理路由?{% 块标题 %}</desc> <question vote="0"> <p>我使用 React 对 symfony 中的页面进行 vite 操作:</p> <p>这是基础:</p> <pre><code><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{% block title %}Welcome!{% endblock %}</title> {# Run `composer require symfony/webpack-encore-bundle` and uncomment the following Encore helpers to start using Symfony UX #} <link rel="shortcut icon" type="image/x-icon" href="{{ asset('images/Logo 2.png') }}"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% block stylesheets %} {{ vite_entry_link_tags('app') }} {% endblock %} <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet"> </head> <body> {% block body %}{% endblock %} {% block javascripts %} {{ vite_entry_script_tags('app') }} {% endblock %} </body> </html> </code></pre> <p>这是树枝:</p> <pre><code>{% extends 'base.html.twig' %} {% block title %}Reseau Sociaux{% endblock %} {% block body %} <div id="app"></div> {% endblock %} </code></pre> <p>这是控制器:</p> <pre><code>/** * @Route("/reseau-sociaux", name="reseau-sociaux_home") * @IsGranted("ROLE_USER") */ public function reseauSociaux(Request $request) { return $this->render('reseauSociaux/reseauSociaux.html.twig'); } </code></pre> <p>这是我的反应:</p> <pre><code>import React from "react"; import { createRoot } from 'react-dom/client'; import Actualite from './pageActualite/Actualite' import './styles/app.css'; import { BrowserRouter, Routes, Route } from "react-router-dom"; import ProfilUser from "./otherPages/ProfilUser/ProfilUser"; const App = () => { return ( <BrowserRouter> <Routes> <Route path="reseau-sociaux" element={<Actualite />}/> <Route path="/reseau-sociaux/profil" element={<ProfilUser />}/> </Routes> </BrowserRouter> ); } const rootElement = document.querySelector('#app'); const root = createRoot(rootElement); root.render(<App />); </code></pre> <p>问题是<strong>route</strong>,react-router-dom运行良好,但是如果我刷新页面,错误是:找不到路由,来自symfony的错误。例如,如果我刷新 /reseau-sociaux/profile 页面,我会收到错误,因为我的 symfony 中没有路由 /reseau-sociaux/profil。</p> <p>我也有其他树枝页面,但它们效果很好</p> </question> <answer tick="false" vote="0"> <p>当然...如果你将路线从<pre><code>/reseau-sociaux</code></pre>延伸到<pre><code>/reseau-sociaux/profil</code></pre>,那就是symfony路线不匹配。你必须 symfony 告诉你的路线可以有子路径。</p> <p>您可以更改路由参数以匹配子路径,例如</p> <pre><code>/** * @Route("/reseau-sociaux/{sub}", name="reseau-sociaux_home", requirements={"sub"=".+"}) * @IsGranted("ROLE_USER") */ public function reseauSociaux(Request $request, ?string $sub = null) { return $this->render('reseauSociaux/reseauSociaux.html.twig'); } </code></pre> </answer> </body></html>

问题描述 投票:0回答:0
reactjs symfony twig react-router-dom vite
© www.soinside.com 2019 - 2024. All rights reserved.