React路由有两种模式,分别是:1、hash模式,该模式会在路径前加入“#”号成为一个哈希值;2、history模式,该模式允许操作浏览器的曾经在标签页或者框架里访问的会话历史记录。
本教程操作环境:Windows10系统、react17.0.1版、Dell G3电脑。
React路由
一、是什么
在单页应用中,一个web项目只有一个html页面,一旦页面加载完成之后,就不用因为用户的操作而进行页面的重新加载或者跳转,其特性如下:
改变 url 且不让浏览器像服务器发送请求
在不刷新页面的前提下动态改变浏览器地址栏中的URL地址
其中主要分成了两种模式:
hash 模式:在url后面加上#,如http://127.0.0.1:5500/home/#/page1
history 模式:允许操作浏览器的曾经在标签页或者框架里访问的会话历史记录
二、使用
React Router对应的hash模式和history模式对应的组件为:
HashRouter
BrowserRouter
这两个组件的使用都十分的简单,作为最顶层组件包裹其他组件,如下所示
// 1.import { BrowserRouter as Router } from "react-router-dom"; // 2.import { HashRouter as Router } from "react-router-dom"; import React from 'react'; import { BrowserRouter as Router, // HashRouter as Router Switch, Route, } from "react-router-dom"; import Home from './pages/Home'; import Login from './pages/Login'; import Backend from './pages/Backend'; import Admin from './pages/Admin'; function App() { return ( <Router> <Route path="/login" component={Login}/> <Route path="/backend" component={Backend}/> <Route path="/admin" component={Admin}/> <Route path="/" component={Home}/> </Router> ); } export default App;
三、实现原理
路由描述了 URL 与 UI之间的映射关系,这种映射是单向的,即 URL 变化引起 UI 更新(无需刷新页面)
下面以hash模式为例子,改变hash值并不会导致浏览器向服务器发送请求,浏览器不发出请求,也就不会刷新页面
hash 值改变,触发全局 window 对象上的 hashchange 事件。所以 hash 模式路由就是利用 hashchange 事件监听 URL 的变化,从而进行 DOM 操作来模拟页面跳转
react-router也是基于这个特性实现路由的跳转
下面以HashRouter组件分析进行展开:
HashRouter
HashRouter包裹了整应用,
通过window.addEventListener('hashChange',callback)监听hash值的变化,并传递给其嵌套的组件
然后通过context将location数据往后代组件传递,如下:
import React, { Component } from 'react'; import { Provider } from './context' // 该组件下Api提供给子组件使用 class HashRouter extends Component { constructor() { super() this.state = { location: { pathname: window.location.hash.slice(1) || '/' } } } // url路径变化 改变location componentDidMount() { window.location.hash = window.location.hash || '/' window.addEventListener('hashchange', () => { this.setState({ location: { ...this.state.location, pathname: window.location.hash.slice(1) || '/' } }, () => console.log(this.state.location)) }) } render() { let value = { location: this.state.location } return ( <Provider value={value}> { this.props.children } </Provider> ); } } export default HashRouter;
Router
Router组件主要做的是通过BrowserRouter传过来的当前值,通过props传进来的path与context传进来的pathname进行匹配,然后决定是否执行渲染组件
import React, { Component } from 'react'; import { Consumer } from './context' const { pathToRegexp } = require("path-to-regexp"); class Route extends Component { render() { return ( <Consumer> { state => { console.log(state) let {path, component: Component} = this.props let pathname = state.location.pathname let reg = pathToRegexp(path, [], {end: false}) // 判断当前path是否包含pathname if(pathname.match(reg)) { return <Component></Component> } return null } } </Consumer> ); } } export default Route;
推荐学习:《react视频教程》
以上是React路由有几种模式的详细内容。更多信息请关注PHP中文网其他相关文章!

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

ReactispupularduetoItsComponent基于结构结构,虚拟,Richecosystem和declarativentation.1)基于组件的harchitectureallowslowsforreusableuipieces。

todebugreactapplicationsefectefectionfection,usethestertate:1)proppropdrillingwithcontextapiorredux.2)使用babortControllerToptopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRaceeDitions.3)intleleassynChronOusOperations.3)

usestate()inrectallowsStateMangementInfunctionalComponents.1)ITSimplifiestTateMempement,MakecodeMoreConcise.2)usetheprevcountfunctionToupdateStateBasedonitspReviousViousViousviousviousVious.3)

selectUsestate()forsimple,独立的StateVariables; useusereducer()forcomplexstateLogicorWhenStatedIppedsonPreviousState.1)usestate()isidealForsImpleUpdatesLikeTogGlikeTogGlikGlingaBglingAboolAboolAupDatingAcount.2)

useState优于类组件和其它状态管理方案,因为它简化了状态管理,使代码更清晰、更易读,并与React的声明性本质一致。1)useState允许在函数组件中直接声明状态变量,2)它通过钩子机制在重新渲染间记住状态,3)使用useState可以利用React的优化如备忘录化,提升性能,4)但需注意只能在组件顶层或自定义钩子中调用,避免在循环、条件或嵌套函数中使用。

useUsestate()forlocalComponentStateMangementighatighation; 1)usestate()isidealforsimple,localforsimple.2)useglobalstate.2)useglobalstateSolutionsLikErcontExtforsharedState.3)

ReusableComponentsInrectenHanceCodainainability and效率byallowingDevelostEsteSeTheseTheseThesAmeCompOntionComponcontRossDifferentPartsofanApplicationorprojects.1)heSredunceReDunceNundSimplifyUpdates.2)yessistensistencyInusErexperience.3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

WebStorm Mac版
好用的JavaScript开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能