如何在Laravel中使用React Router? [英] How to use React Router with Laravel?
问题描述
我需要使用 React Router
并使用 Laravel
项目。
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' => '.*']
]);
然后在您的控制器中,只显示包含反应根文档的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 you're controller is only returning a view (like in the example above), you can swap out 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屋!