router
-
Route参数
<Route path='/' exact={true} component={Home} > </Route> <Route path='/about' render={props => <About {...props} />} > </Route> <Route path='/dashboard1' children={Dashboard} > </Route> <Route path='/dashboard2' children={(props) => <Dashboard {...props} />} > </Route> component 可以是类组件 不能是组件实例; 也可以是函数组件 render渲染的组件,可以是函数组件, 不能是类组件, 在切换路由之后会卸载, 而children渲染的组件不会卸载, 只会调用一次 children 不管路径是否匹配都会渲染 只能是函数组件 通过props.match可以判断当前组件是否是匹配的
-
router相关
import { BrowserRouter, Route, NavLink, Switch, withRouter, Redirect } from 'react-router-dom' // 给组件添加路由信息 @withRouter class MyNavLink extends Component { render() { const pathname = this.props.location.pathname; this.props.history.push('/home'); return <div> </div> } } const Home = withRouter((props) => <div>Home</div>); render() { return <> <Route path="/home"> <Home></Home> </Route> <Redirect from='/' to='/home' /> </> } ```
-
Redirect & 传参
function loginPage() { const { state: { from } } = useLocation(); const history = useHistory(); function login() { // history.push(from); history.replace(from); } return <div> 页面来自于: {from} </div> } const PrivateRoute = ({ children, ...rest }) => { const { pathname } = useLocation(); return ( <Route {...rest}> {isAuth ? children : <Redirect to={{ path: '/login', state: { from: pathname } }}>} </Route> ) } ```
-
取参数
// /about/:id // <NavLink to="/about/123"></NavLink> // <NavLink to={{ pathname: '/about', state: { id: 12 } }}></NavLink> // <NavLink to={{ pathname: '/about?sw=345', state: { id: 12 } }}></NavLink> const About = function() { const { id } = useParams(); const { state: { id }, search } = useLocation(); const query = new URLSearchParams(search); const sw = query.get('sw'); return <> Params { id } </> } ```
-
Page 404
const Page404 = () => { return <> 404 </> } <Route path="*"> <Page404 /> </Route> ```
-
Route Config
<Switch> {routes.map((item, index) => ( <Route key={index} path={route.path} exact={route.exact} children={<route.main />} > </Route> ))} </Switch> ```
-
Children Config
const routes = [ { path: '/a', component: Home }, { path: '/b', component: About, children: [ { path: '/b1', component: About1, }, { path: '/b2', component: About2, } ] }, ] <div> {route.map((item,index) => { let { path } = item; return ( <Route key={path} path={path} > <RouteWithSubRoutes {...props} route={item}></RouteWithSubRoutes> </RouteW> ) }} </div> function About(props) { const { routes } = props; return <> <Switch> {routes.map(item => ( <Route key={item.path} path={item.path} > <RouteWithSubRoutes {...props } key={item.path} route={item} > </Route> ))} </Switch> </> } function RouteWithSubRoutes(props) { const { route } = props return ( <route.component {...props} routes={route.children} > </route.component> ) } ```