一、react-router-dom v5路由信息获取
HomeHead.jsx:
import React from "react";
import {Link, withRouter, useHistory, useLocation, useRouteMatch} from 'react-router-dom'
import styled from "styled-components";
const NavBox = styled.nav`
a {
margin-right: 10px;
}
`;
// const HomeHead = function() {
// return (
// <NavBox>
// <Link to="/a">A</Link>
// <Link to="/b">B</Link>
// <Link to="/c">C</Link>
// </NavBox>
// )
// }
class HomeHead extends React.Component{
render() {
console.log(this.props);
return (
<NavBox>
<Link to="/a">A</Link>
<Link to="/b">B</Link>
<Link to="/c">C</Link>
</NavBox>
)
}
}
// const Handle = function(Component) {
// return function Hoc(props) {
// let history = useHistory(),
// location = useLocation(),
// match = useRouteMatch()
// return <Component {...props} history={history} location={location} match={match} />
// }
// }
export default withRouter(HomeHead)
App.jsx:
import "./App.css";
// import { Button } from "antd-mobile";
import styled from "styled-components";
import { HashRouter, Route, Switch, Redirect, Link } from "react-router-dom";
import A from './views/A'
import B from './views/B'
import C from './views/C'
import Login from './views/Login'
import routes from "./router/routes";
import RouterView from "./router";
// import { Suspense } from 'react'
import HomeHead from './components/HomeHead'
const NavBox = styled.nav`
a {
margin-right: 10px;
}
`;
const App = function App() {
return (
<HashRouter>
<div className="App">
{/* 导航部分 */}
{/* <NavBox>
<Link to="/a">A</Link>
<Link to="/b">B</Link>
<Link to="/c">C</Link>
</NavBox> */}
<HomeHead test='aa'/>
{/* 路由容器 */}
<div className="content">
{/*
Switch:确保路由中,只要有一项匹配,就不会继续往下匹配路由
exact:设置匹配模式为精准匹配
*/}
{/* <Switch>
<Redirect exact from='/' to='/a' />
<Route path='/a' component={A} ></Route>
<Route path='/b' component={B}></Route>
<Route path='/c' render={() => {
let isLogin = true
if(isLogin) {
return <C />
}
return <Redirect to='/login' />
}}></Route>
<Route path='/login' component={Login}></Route>
<Redirect to='/a'/>
</Switch> */}
<RouterView routes={routes}/>
</div>
</div>
</HashRouter>
);
}
export default App;
router/index.jsx:
import React, { Suspense } from "react";
import { Switch, Route, Redirect } from "react-router-dom";
const RouterView = function (props) {
let { routes } = props;
return (
<Switch>
{routes.map((route, index) => {
let {
redirect,
exact,
from,
to,
path,
component: Component,
name,
meta,
} = route;
let config = {};
if (redirect) {
config = { to };
if (from) config.from = from;
if (exact) config.exact = exact;
return <Redirect key={index} {...config} />;
}
config = { path };
if (exact) config.exact = exact;
// return <Route key={index} {...config} component={Component} />
return (
<Route
key={index}
{...config}
render={(props) => {
// console.log(props, "props");
return (
<Suspense fallback={<h2>加载中。。。</h2>}>
<Component {...props} />
</Suspense>
);
}}
/>
);
})}
</Switch>
);
};
export default RouterView;