emmmmmmmm,当写到这里的时候,整理了一下手里几个项目,发现路由随着业务变化,不是那么好做统一的封装,比如
- 有的菜单切换在左侧Menu中,有的在顶部
- 有的想要
HashRouter,有的想要HistoryRouter
所以这里只提供react-router、react-router-dom一些简单的用法吧
Hash模式和History模式有什么区别
(还是忍不住八股文了)
先理解路由到底做了什么
- 相对于以往的单页面,根据浏览器url访问不同的静态页面资源
- 前端路由是根据url不同,显示不同部分页面内容,但是访问的一直是
同一个html。只是两种模式实现方式略有不同
Hash模式
- 通过
hashchange事件监听url变化(window.onhashchange) - url后面带一个
#很不美观
History模式
- 利用window.history提供的
pushState、replaceState来记录路由状态
但是如果不同url,按理说不应该不同的url对应不同的静态资源才对吗?
所以History模式又需要后端配合,比如nginx配置
server {
listen 80;
server_name xxx.com;
location / {
index /data/xxx/index.html;
try_files $uri $uri/ /index.html;
}
}
上面这样,访问的url,就永远返回index.html这个单文件。就可以实现history的不同url访问了
路由组件使用
好了好了,跑题了!!!!!!!!!!!!!!!!!
这里主要是使用React相关的路由组件
const index = () => {
return <div className="page" >
<div className="content" >
<BrowserRouter>
<Link to="/children">children</Link>
<Link to="/home">home</Link>
<Link to="/list">list</Link>
<Switch>
<Route component={Children} /* children 组件 */
path="/children"
></Route>
<Route component={Home} /* home 组件 */
path={'/home'}
></Route>
<Route component={List} /* list 组件 */
path="/list"
></Route>
</Switch>
</BrowserRouter>
</div>
</div>
}
具体的按照官网文档和具体的项目业务逻辑使用就可以。比如鉴权、二级菜单等
其他
在研究这些组件的时候发现,大部分组件现在实现的状态传递基本都是使用的React.Context。比如Antd、Route、Redux