我正在使用反应路由器进行练习,需要有一个:id
参数。它与网址中的ID匹配,例如/edit/2
,但不包含/edit
的基本情况。
主应用路由器文件
import React from 'react';
import {BrowserRouter, Route, Switch, Link, NavLink} from 'react-router-dom';
import landingPage from '../components/landingPage';
import editPage from '../components/editPage';
import createPage from '../components/createPage';
import helpPage from '../components/helpPage';
import notFoundPage from '../components/notFoundPage';
import Header from '../components/header';
const AppRouter = () => (
<BrowserRouter>
<div>
<Header/>
<Switch>
<Route exact={true} path="/" component={landingPage}/>
<Route path="/create" component={createPage}/>
<Route exact={false} path="/edit/:id" component={editPage}/>
<Route path="/help" component={helpPage}/>
<Route component={notFoundPage}/>
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;
编辑页面代码
import React from 'react';
const editPage = (props) => {
console.log(props)
return (
<div>Edit Page</div>
);
}
export default editPage;
答案 0 :(得分:1)
如果您使用的是React Router&gt; = v4,则可以make a parameter optional在参数名称后添加?
:
<Route exact={false} path="/edit/:id?" component={editPage}/>