位置: IT常识 - 正文
推荐整理分享React(五) —— 路由的使用(react5),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:react route,reactrouter,reactrouter,react withrouter,react中的路由,reactrouter,react5,react-router5,内容如对您有帮助,希望把文章链接给更多的朋友!
🧁个人主页:个人主页
✌支持我 :点赞👍收藏🌼关注🧡
文章目录⛳React 路由🔮路由简介1.什么是路由2.路由安装🧩路由的使用(1)路由方法导入(2)定义路由(3)路由重定向(4)嵌套路由(5)路由跳转方式(6)路由传参(7)路由拦截(8)路由模式HashRouter模式BrowserRouter模式额外命名(9)withRouter🏫项目注意反向代理CSSModule⛳React 路由🔮路由简介1.什么是路由📍路由是根据不同的 url 地址显示不同的内容或页面 📍一个针对React而设计的路由解决方案,可以友好的帮助解决React components到URL之间的同步映射关系
2.路由安装npm install react-router-dom@5🧩路由的使用(1)路由方法导入import React, { Component } from 'react'import {HashRouter,Route} from 'react-router-dom'(2)定义路由 <HashRouter> <Route path='/films' component={Films}/> <Route path='/cinemas' component={Cinemas}/> <Route path='/center'component={Center}>1111</Route> </HashRouter>(3)路由重定向💧1. 会导航到一个新的位置,新的位置将覆盖历史堆栈中的当前条目,例如服务器端重定向 💧2. 当用户访问某界面时,若该界面并不存在,则需跳转到一个我们自定义的界面,此时需要用Redirect重定向
//引入redirectimport {HashRouter,Redirect,Route} from 'react-router-dom'..................................<Redirect from='/' to="/films"></Redirect>💧1. from: string => 要从中进行重定向的路径名
💧2. to:string => 要重定向到的位置
以上为模糊匹配,凡是以/开头的都会跳转到films
解决
引入Switch组件
import {HashRouter,Redirect,Route,Switch} from 'react-router-dom'....................................<Switch> <Route path='/films' component={Films}/> <Route path='/cinemas' component={Cinemas}/> <Route path='/center'component={Center}>1 {/* 模糊匹配 凡是以/开头的都会跳转到films*/} <Redirect from='/' to="/films"></Redirect></Switch>Switch如switch语句一样,若匹配到,则不在匹配;若均未匹配到,则跳转到自定义的界面films
注意:Redirect必须放在Switch里的最后一行,表示上面路由都匹配不到,则跳转到“/films”组件
精准匹配
//语法<Redirect from='/' to="/films" exact></Redirect>加上 exact 表示精确匹配,只有完全是"/“时才会跳转到”/films"界面
............................................<Switch> <Route path='/films' component={Films}/> <Route path='/cinemas' component={Cinemas}/> <Route path='/center'component={Center}>1111</Route> {/* 模糊匹配 凡是以/开头的都会跳转到films*/} <Redirect from='/' to="/films"></Redirect> {/* 精确匹配 */} <Redirect from='/' to="/films" exact></Redirect> <Route component={NotFound}></Route> </Switch>当输入的路径都不匹配时,则会跳转到 NotFound界面
(4)嵌套路由//films组件中<Switch> <Route path='/films/nowplaying' component={nowplaying}></Route> <Route path='/films/Comingsoon' component={Comingsoon}></Route> <Redirect from="/films" to="/films/nowplaying"></Redirect></Switch>(5)路由跳转方式上一篇:AJAX中的跨域(CORS) 问题 (更新于2023.02.04)(ajax跨域请求的原理是什么)
下一篇:手把手带你调参Yolo v5(一)(调参数是什么意思)
友情链接: 武汉网站建设