React Router 无法识别 Laravel 中的直接地址行更改

我使用 React Router 和 Laravel。当我浏览 Link 元素时一切正常,但是当我更改浏览器地址行以手动显示另一个组件时,Laravel 显示它默认的 404 页面。

这是默认的 web.php 内容,在welcome.blade.php 中我包含 js/app.js 文件:

Route::get('/', function () { 
  return view('welcome');
});

这是我的 App.js 内容:

import React from 'react';

import { Switch, Route } from "react-router-dom";

import Signin from "../../containers/Signin";

import Signup from "../../containers/Signup";

import Error from "../../containers/Error";

import Courses from "../../containers/Courses";

import Course from "../../containers/Course";

import Quiz from "../../containers/Quiz";

import Header from "../Header";

import "./App.css";

import Library from "../../containers/Library";

import QuizResults from "../../containers/QuizResults";

import Main from "../Main";

import StudentsList from "../../containers/StudentsList";



function App()

{

  return (

    <div className="App">


      <Header isLogged={false}/>


      <Switch>


        <Route exact path='/' component={Signin} />

        <Route path='/signup' component={Signup} />



        <Main>

          <Route path='/courses' component={Courses} />

          <Route path='/course/:id' component={Course} exact/>

          <Route path='/quiz' component={Quiz} />

          <Route path='/library' component={Library} />

          <Route path='/quiz-results' component={QuizResults} />

          <Route path='/students' component={StudentsList} />

        </Main>


        <Route component={Error} />


      </Switch>


    </div>

  );

}


export default App;

应用程序.js:



import React from 'react';

import ReactDOM from 'react-dom';

import { BrowserRouter } from 'react-router-dom';

import App from './components/App';

import './index.css';



ReactDOM.render(

  <React.StrictMode>

    <BrowserRouter>

      <App />

    </BrowserRouter>

  </React.StrictMode>,

  document.getElementById('root')

);


那么,如何强制 React Router 对直接浏览器地址行更改做出反应?


UYOU
浏览 121回答 1
1回答

FFIVE

因为您使用 SPA,所以您需要web.php像这样配置Route::any('{all}', function () {&nbsp; &nbsp; return view('welcome');})->where('all', '^(?!api).*$')->where('all', '^(?!storage).*$');然后反应路由器将捕获所有路由这里api和storageroutes被排除在catch之外,所以你可以使用存储文件和api来调用api
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript