一般有react-router
v4和React的大菜鸟。我尝试设置两条父路线:/
和/dashboard
。 /
将成为登录/注册/等的登录页面,而/ dashboard将是经过身份验证的区域。我有点麻烦让子路由按照文档进行操作而这个SO回答here
设置非常简单。这是我的app.js
(路由/
和/dashboard
正常工作):
import React from 'react'
import {Route, BrowserRouter, Switch} from 'react-router-dom'
import LandingPage from "./components/landing/LandingPage";
import ETFApp from "./components/dashboard/ETFApp";
class App extends React.Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={LandingPage}/>
<Route path="/dashboard" component={ETFApp}/>
</Switch>
</BrowserRouter>
)
}
}
export default App;
但我的LandingPage
组件的子路线似乎不起作用,尤其是/signup
和/login
。我有预感我做错了。:
import React, {PropTypes} from 'react';
import {Link, Route} from 'react-router-dom';
import {ToolbarGroup, ToolbarTitle, RaisedButton, Toolbar} from 'material-ui'
import HomeCard from "./HomeCard";
import LoginPage from "../../containers/LoginPage";
import SignUpPage from "../../containers/SignUpPage";
const LandingPage = ({match}) => {
return (
<div>
<Toolbar>
<ToolbarGroup>
<Link to="/">
<ToolbarTitle text="ETFly"/>
</Link>
</ToolbarGroup>
<ToolbarGroup>
<RaisedButton label="Login" primary={true} containerElement={<Link to="/login">Log in</Link>}/>
<RaisedButton label="Sign up" primary={true} containerElement={<Link to="/signup">Sign up</Link>}/>
</ToolbarGroup>
</Toolbar>
<Route path={match.url} exact component={HomeCard}/>
<Route path={`${match.url}/login`} component={LoginPage}/>
<Route path={`${match.url}/signup`} component={SignUpPage}/>
</div>
);
};
LandingPage.propTypes = {
match: PropTypes.object.isRequired
}
export default LandingPage;
编辑:我已删除LandingPage
组件中的切换,因为它与文档here类似,但仍然没有用。我也不再使用match
道具:
<Route path="/" component={HomeCard}/>
<Route path="/login" component={LoginPage}/>
<Route path="/signup" component={SignUpPage}/>
看起来组件没有在React Dev Tools中呈现:
任何帮助表示赞赏。感谢。
答案 0 :(得分:2)
使用exact
道具时,只有提供的路径匹配。
<Route exact path='/' component={LandingPage} />
// only matches the pathname "/"
您必须从路线中移除exact
道具才能使其与/login
和/signup
路径名匹配。但是,这样做是行不通的,因为路径也会匹配/dashboard
路径名。解决这个问题的最佳方法是在<Switch>
<Switch>
<Route path='/dashboard' component={ETFApp}/>
<Route path='/' component={LandingPage}/>
</Switch>