我正在尝试使用 ReactJS 构建 Laravel 项目。我已经在表格上显示了数据。但是,当我添加一些链接,如 Create, Edit, Delete... 时,出现了一些错误:
- Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`.
- Uncaught Error: You should not use `Link` outside a `Router`
所以:
- 我创建 RoutePath.js 只是为了创建路由,但我不知道如何将它们导入 Example.js
- 单击添加页面、编辑页面...时,它会重定向到空白页面,而不是主页下方。但是,添加页面似乎会在首页下方
我是新手所以请帮助我。谢谢。这是我的代码:
示例.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Link} from "react-router-dom";
import CreatePost from './CreatePost';
import RoutePath from '../routes/RoutePath';
...
postRow(p){
return (
<tr key = {p.id}>
<td>{p.title}</td>
<td>{p.description}</td>
<td><Link to='/edit'></Link></td>
<td><Link to='/delete'></Link></td>
</tr>
)
}
render() {
const posts = this.state.posts.map(post => this.postRow(post));
return (
<div>
<table border="1">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{ posts }
</tbody>
</table>
<div>
<Link to='/add-post'>Add</Link>
</div>
</div>
);
}
}
ReactDOM.render(
<Example />
, document.getElementById('homepage')
);
RoutePath.js
import React, {Component} from 'react';
import { Route, BrowserRouter } from "react-router-dom";
import CreatePost from '../components/CreatePost';
import Example from '../components/Example';
export default class RoutePath extends Component{
render(){
return(
<BrowserRouter>
<div>
<Route exact path='/' component={Example}/>
<Route path='/add-post' component={CreatePost}/>
<Route path='/edit' component={Edit}/>
</div>
</BrowserRouter>
)
}
}
最佳答案
这对我有用...我的单页应用程序的单一 View 是 home.blade.php
并且我在我的 中使用
BrowserRouter
应用程序.js
Route::get('/', function () {
return view('home');
});
Route::get('/{route}',function(){
return view('home');
});
这将允许您转到 http://localhost/并获取应用程序的主页或http://localhost/about-us并获取“关于我们”的路线。
这是一种比使用看起来有点丑陋的 HashRouter 更好的方法:http://localhost/#/about-us
关于reactjs - Laravel 中的 react 路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942203/