我正在尝试使用react-router-dom,但我无法理解如何定义一个“主”容器,它将打开里面的所有其他组件? 在过去的旧版本中
<Router history={history}>
<Route path="/" component={Main}>
<IndexRoute component={ShowsPage} />
<Route path="/shows" component={ShowsPage} />
<Route path="/tickets" component={ticketsPage} />
</Route>
<Redirect from="*" to="/" />
</Router>
它会像魔术一样工作,现在我尝试了类似的东西
<Router>
<div>
<Route component={Main}/>
<Route path="/" exact component={ShowsPage}/>
<Route path="/tickets" exact component={ticketsPage}/>
<Route path="/shows" exact component={ShowsPage}/>
</div>
</Router>
我不确定如何实现未发现的路由,但是在我最后一次尝试处理路径时,我设法让它们在容器内打开,但我也得到了这个警告The prop `children` is marked as required in `Main`, but its value is `undefined
我想知道为什么我抓住他们 ?我做错了什么?以及如何设置每个其他路由(除了定义的)将被重定向到“/”(到ShowsPage组件)
这是Main.js(我的主要容器)
import React from 'react';
import PropTypes from 'prop-types';
import HeaderContainer from './HeaderContainer';
import FooterContainer from './FooterContainer';
const Main = ({children}) => (
<div>
<container className="containerHeader">
<HeaderContainer />
</container>
<container className="containerMain">
{children}
</container>
<container className="containerFooter">
<FooterContainer />
</container>
</div>
)
Main.propTypes = {
children: PropTypes.object.isRequired,
}
export default Main;
谢谢!
答案 0 :(得分:2)
<Route component={Main}/>
<Route path="/" exact component={ShowsPage}/>
<Route path="/tickets" exact component={ticketsPage}/>
<Route path="/shows" exact component={ShowsPage}/>
应该是
<Route component={Main} />
在Main的render方法中添加Route。将它们放在Switch中(从react-router-dom导入),如下所示
<Switch>
<Route path="/" exact component={ShowsPage}/>
<Route path="/tickets" exact component={ticketsPage}/>
<Route path="/shows" exact component={ShowsPage}/>
</Switch>
答案 1 :(得分:2)
假设您要在ShowsPage
组件内显示ticketsPage
,ShowsPage
和Main
。
您必须将这些组件路由放在Main
组件
将history
道具添加到Router
import createBrowserHistory from 'history/createBrowserHistory'
const browserHistory = createBrowserHistory();
<Router history={browserHistory}>
<div>
<Route path="/" component={Main} />
</div>
</Router>
将子组件路径移动到main(父)组件中。
const Main = ({ match }) => { //assume main component.
return (<div>
This is the Root component.
<Route path={`${match.url}`} exact component={ShowsPage} ></Route>
<Route path={`${match.url}tickets`} exact component={ticketsPage}></Route>
<Route path={`${match.url}shows`} exact component={ShowsPage}></Route>
</div>)
};