在我的应用中,我有路线
页面中的常见部分放在Auth.jsx
中,使用路由器/auth/login
和/auth/regster
但/auth/login/xxx
也会匹配/auth/login
要解决的唯一解决方案是在任何地方添加exact
,Switch
和Error Route
是否还有其他任何解决方法可以避免编写过多的Error Route
?
代码跟随......
App.jsx
import React from 'react'
import { render } from 'react-dom'
import { Route, Switch } from 'react-router-dom'
import Error from './Error'
import Home from './Home/Home'
import Auth from './Auth/Auth'
export default class App extends React.Component {
render () {
return (
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/auth" component={Auth}/>
<Route component={Error}/>
</Switch>
)
}
}
Auth.jsx
import React from 'react'
import { render } from 'react-dom'
import { Route, Link } from 'react-router-dom'
import Login from './Login'
import Register from './Register'
export default class Auth extends React.Component {
render () {
return (
<div>
<div>Auth works</div>
<div>
<Link to={`${this.props.match.url}/login`}>LOGIN</Link>
<Link to={`${this.props.match.url}/register`}>REGISTER</Link>
</div>
<Route exact path={`${this.props.match.url}/login`} component={Login}/>
<Route exact path={`${this.props.match.url}/register`} component={Register}/>
</div>
);
}
}