如何在 Laravel 中使用 React Router? [英] How to use React Router with Laravel?

查看:22
本文介绍了如何在 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');

这篇关于如何在 Laravel 中使用 React Router?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆