路由demo&&深入了解【以防忘记】
常见问题一:this.props中history、location、match丢失问题
- withRouter的作用:将react-router的 history、location、match 三个对象传入props对象上
- 默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用编程式导航的写法,执行this.props.history.push(’/detail’)跳转到对应路由的页面然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props
import React from "react";
import { withRouter } from "react-router-dom";//tip
class Home extends React.Component {
render() {
return <div>zujian</div>
}
}
export default withRouter(Home)//tip
超简化版本
const App = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
ReactDOM.render(
<App />,
document.getElementById('root')
);
左侧Menu菜单联动右侧路由
//index.tsx入口文件
import { Switch, Route, HashRouter } from 'react-router-dom';
const App = () => {
return (
<HashRouter> //使用路由为hash路由,以防地址栏#之前随意变动
<Shell>
<Switch>
{
routes.map(route => { //以数组形式引入route.js里面的,遍历绑定路由
const { Component, key, exact, path } = route;
return (
<Route key={key} path={path} exact={exact}>
<Component />
</Route>
)
})
}
</Switch>
</Shell>
</HashRouter >
)
}
//routes.js里面的路由格式,以数组形式存在
import Title from './Pages/Text/GreateTitle/index';
const AppRoutes = [
{
path: '/',
key: 'title',
exact: true,
Component: Title,
},
{
path: '/title',
key: 'title',
exact: true,
Component: Title,
},
...todo
];
export default AppRoutes;
//Shell里的写法
export default function Shell(props: any) {
return (
<div className='multi-app'>
<Header />//不变的组件
<div className='multi-app-body'>
<div className='Nav'>
<Nav />//不变的组件
</div>
<div className='pages'>
{props.children}//变动的组件
</div>
</div>
</div>
)
}