如何在 Laravel 中使用 React Router?

2022-01-02 00:00:00 reactjs php javascript laravel react-router

我需要在 Laravel 项目中使用 React Router.

I needing use React Router with a Laravel project.

但是当我在 React Router 上创建路由器并尝试访问时,Laravel 指责路由不存在错误.

But when I create router on the React Router and try access, Laravel accuse Route not exist error.

如何使用 React Router 来管理 Laravel 项目路由?

How to can I use React Router to manager Laravel project routes?

render((
    <Router history={browserHistory}>
        <Route path="/" component={App}/>
        <Route path="/profile" component={Profile}/> // this route I trying access
    </Router>
), document.getElementById('root'));

推荐答案

创建一个将所有内容映射到一个控制器的路由,如下所示:

Create a route that maps everything to one controller, like so:

Route::get('/{path?}', [
    'uses' => 'ReactController@show',
    'as' => 'react',
    'where' => ['path' => '.*']
]);

然后在您的控制器中,只显示包含 react 根文档的 HTML 页面:

Then in your controller, just show the HTML page that contains the react root document:

class ReactController extends Controller {
    public function show () {
        return view('react');
    }
}

然后用反应路由器做一切正常的事情.似乎对我来说效果很好.

Then do everything as normal with react router. Seems to work well for me.

Laravel 5.5 更新如果你的控制器只返回一个视图(如上面的例子),你可以在你的路由文件中用这个替换上面的所有代码:

Update for Laravel 5.5 If your controller only returns a view (like in the example above), you can replace all of the above code with this in your routes file:

Route::view('/{path?}', 'path.to.view')
     ->where('path', '.*')
     ->name('react');

相关文章