国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服務器之家 - 編程語言 - JavaScript - React - react實現瀏覽器自動刷新的示例代碼

react實現瀏覽器自動刷新的示例代碼

2022-03-09 16:06LouisWK React

這篇文章主要介紹了react實現瀏覽器自動刷新的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

在單頁應用如此流行的今天,曾經令人驚嘆的前端路由已經成為各大框架的基礎標配,每個框架都提供了強大的路由功能,導致路由實現變的復雜。想要搞懂路由內部實現還是有些困難的,但是如果只想了解路由實現基本原理還是比較簡單的。本文針對前端路由主流的實現方式 hash 和 history,提供了原生JS/React/Vue 共計六個版本供參考,每個版本的實現代碼約 25~40 行左右(含空行)。

什么是前端路由?

路由的概念來源于服務端,在服務端中路由描述的是 URL 與處理函數之間的映射關系。

在 Web 前端單頁應用 SPA(Single Page Application)中,路由描述的是 URL 與 UI 之間的映射關系,這種映射是單向的,即 URL 變化引起 UI 更新(無需刷新頁面)。

如何實現前端路由?

要實現前端路由,需要解決兩個核心問題:

如何改變 URL 卻不引起頁面刷新?如何檢測 URL 變化了?

下面分別使用 hash 和 history 兩種實現方式回答上面的兩個核心問題。

hash 實現

  • hash 是 URL 中 hash (#) 及后面的那部分,常用作錨點在頁面內進行導航,改變 URL 中的 hash 部分不會引起頁面刷新
  • 通過 hashchange 事件監聽 URL 的變化,改變 URL 的方式只有這幾種:通過瀏覽器前進后退改變 URL、通過標簽改變 URL、通過window.location改變URL,這幾種情況改變 URL 都會觸發 hashchange 事件

history 實現

  • history 提供了 pushState 和 replaceState 兩個方法,這兩個方法改變 URL 的 path 部分不會引起頁面刷新
  • history 提供類似 hashchange 事件的 popstate 事件,但 popstate 事件有些不同:通過瀏覽器前進后退改變 URL 時會觸發 popstate 事件,通過pushState/replaceState或標簽改變 URL 不會觸發 popstate 事件。好在我們可以攔截 pushState/replaceState的調用和標簽的點擊事件來檢測 URL 變化,所以監聽 URL 變化可以實現,只是沒有 hashchange 那么方便。

 原生JS版前端路由實現

基于上節討論的兩種實現方式,分別實現 hash 版本和 history 版本的路由,示例使用原生 HTML/JS 實現,不依賴任何框架。

基于 hash 實現

運行效果:

react實現瀏覽器自動刷新的示例代碼

HTML 部分:

<body>
  <ul>
ref="">    <!-- 定義路由 -->
    <li><a href="#/home" rel="external nofollow" >home</a></li>
    <li><a href="#/about" rel="external nofollow" >about</a></li>
 
ref="">    <!-- 渲染路由對應的 UI -->
    <div id="routeView"></div>
  </ul>
</body>

JavaScript 部分:

// 頁面加載完不會觸發 hashchange,這里主動觸發一次 hashchange 事件
window.addEventListener("DOMContentLoaded", onLoad)
// 監聽路由變化
window.addEventListener("hashchange", onHashChange)
 
// 路由視圖
var routerView = null
 
function onLoad () {
  routerView = document.querySelector("#routeView")
  onHashChange()
}
 
// 路由變化時,根據路由渲染對應 UI
function onHashChange () {
  switch (location.hash) {
    case "#/home":
      routerView.innerHTML = "Home"
      return
    case "#/about":
      routerView.innerHTML = "About"
      return
    default:
      return
  }
}

基于 history 實現

運行效果:

react實現瀏覽器自動刷新的示例代碼

HTML 部分:

<body>
  <ul>
    <li><a href="/home">home</a></li>
    <li><a href="/about">about</a></li>
 
    <div id="routeView"></div>
  </ul>
</body>

JavaScript 部分:

// 頁面加載完不會觸發 hashchange,這里主動觸發一次 hashchange 事件
window.addEventListener("DOMContentLoaded", onLoad)
// 監聽路由變化
window.addEventListener("popstate", onPopState)
 
// 路由視圖
var routerView = null
 
function onLoad () {
  routerView = document.querySelector("#routeView")
  onPopState()
 
 href="">  // 攔截 <a> 標簽點擊事件默認行為, 點擊時使用 pushState 修改 URL并更新手動 UI,從而實現點擊鏈接更新 URL 和 UI 的效果。
  var linkList = document.querySelectorAll("a[href]")
  linkList.forEach(el => el.addEventListener("click", function (e) {
    e.preventDefault()
    history.pushState(null, "", el.getAttribute("href"))
    onPopState()
  }))
}
 
// 路由變化時,根據路由渲染對應 UI
function onPopState () {
  switch (location.pathname) {
    case "/home":
      routerView.innerHTML = "Home"
      return
    case "/about":
      routerView.innerHTML = "About"
      return
    default:
      return
  }
}

React 版前端路由實現

基于 hash 實現

運行效果:

react實現瀏覽器自動刷新的示例代碼

使用方式和 react-router 類似:

  <BrowserRouter>
    <ul>
      <li>
        <Link to="/home">home</Link>
      </li>
      <li>
        <Link to="/about">about</Link>
      </li>
    </ul>
 
    <Route path="/home" render={() => <h2>Home</h2>} />
    <Route path="/about" render={() => <h2>About</h2>} />
  </BrowserRouter>

BrowserRouter 實現

export default class BrowserRouter extends React.Component {
  state = {
    currentPath: utils.extractHashPath(window.location.href)
  };
 
  onHashChange = e => {
    const currentPath = utils.extractHashPath(e.newURL);
    console.log("onHashChange:", currentPath);
    this.setState({ currentPath });
  };
 
  componentDidMount() {
    window.addEventListener("hashchange", this.onHashChange);
  }
 
  componentWillUnmount() {
    window.removeEventListener("hashchange", this.onHashChange);
  }
 
  render() {
    return (
      <RouteContext.Provider value={{currentPath: this.state.currentPath}}>
        {this.props.children}
      </RouteContext.Provider>
    );
  }
}

Route 實現

export default ({ path, render }) => (
  <RouteContext.Consumer>
    {({currentPath}) => currentPath === path && render()}
  </RouteContext.Consumer>
);

Link 實現

export default ({ to, ...props }) => <a {...props} href={"#" + to} />;

基于 history 實現

運行效果:

react實現瀏覽器自動刷新的示例代碼

使用方式和 react-router 類似:

  <HistoryRouter>
    <ul>
      <li>
        <Link to="/home">home</Link>
      </li>
      <li>
        <Link to="/about">about</Link>
      </li>
    </ul>
 
    <Route path="/home" render={() => <h2>Home</h2>} />
    <Route path="/about" render={() => <h2>About</h2>} />
  </HistoryRouter>

HistoryRouter 實現

export default class HistoryRouter extends React.Component {
  state = {
    currentPath: utils.extractUrlPath(window.location.href)
  };
 
  onPopState = e => {
    const currentPath = utils.extractUrlPath(window.location.href);
    console.log("onPopState:", currentPath);
    this.setState({ currentPath });
  };
 
  componentDidMount() {
    window.addEventListener("popstate", this.onPopState);
  }
 
  componentWillUnmount() {
    window.removeEventListener("popstate", this.onPopState);
  }
 
  render() {
    return (
      <RouteContext.Provider value={{currentPath: this.state.currentPath, onPopState: this.onPopState}}>
        {this.props.children}
      </RouteContext.Provider>
    );
  }
}

Route 實現

export default ({ path, render }) => (
  <RouteContext.Consumer>
    {({currentPath}) => currentPath === path && render()}
  </RouteContext.Consumer>
);

Link 實現

export default ({ to, ...props }) => (
  <RouteContext.Consumer>
    {({ onPopState }) => (
      <a
        href=""
        {...props}
        onClick={e => {
          e.preventDefault();
          window.history.pushState(null, "", to);
          onPopState();
        }}
      />
    )}
  </RouteContext.Consumer>
);

Vue 版本前端路由實現

基于 hash 實現

運行效果:

react實現瀏覽器自動刷新的示例代碼

使用方式和 vue-router 類似(vue-router 通過插件機制注入路由,但是這樣隱藏了實現細節,為了保持代碼直觀,這里沒有使用 Vue 插件封裝):

    <div>
      <ul>
        <li><router-link to="/home">home</router-link></li>
        <li><router-link to="/about">about</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
 
const routes = {
  "/home": {
    template: "<h2>Home</h2>"
  },
  "/about": {
    template: "<h2>About</h2>"
  }
}
 
const app = new Vue({
  el: ".vue.hash",
  components: {
    "router-view": RouterView,
    "router-link": RouterLink
  },
  beforeCreate () {
    this.$routes = routes
  }
})

router-view 實現:

<template>
  <component :is="routeView" />
</template>
 
<script>
import utils from "~/utils.js"
export default {
  data () {
    return {
      routeView: null
    }
  },
  created () {
    this.boundHashChange = this.onHashChange.bind(this)
  },
  beforeMount () {
    window.addEventListener("hashchange", this.boundHashChange)
  },
  mounted () {
    this.onHashChange()
  },
  beforeDestroy() {
    window.removeEventListener("hashchange", this.boundHashChange)
  },
  methods: {
    onHashChange () {
      const path = utils.extractHashPath(window.location.href)
      this.routeView = this.$root.$routes[path] || null
      console.log("vue:hashchange:", path)
    }
  }
}
</script>

router-link 實現:

<template>
  <a @click.prevent="onClick" href=""><slot></slot></a>
</template>
 
<script>
export default {
  props: {
    to: String
  },
  methods: {
    onClick () {
      window.location.hash = "#" + this.to
    }
  }
}
</script>

基于 history 實現

運行效果:

react實現瀏覽器自動刷新的示例代碼

使用方式和 vue-router 類似:

    <div>
      <ul>
        <li><router-link to="/home">home</router-link></li>
        <li><router-link to="/about">about</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
 
const routes = {
  "/home": {
    template: "<h2>Home</h2>"
  },
  "/about": {
    template: "<h2>About</h2>"
  }
}
 
const app = new Vue({
  el: ".vue.history",
  components: {
    "router-view": RouterView,
    "router-link": RouterLink
  },
  created () {
    this.$routes = routes
    this.boundPopState = this.onPopState.bind(this)
  },
  beforeMount () {
    window.addEventListener("popstate", this.boundPopState) 
  },
  beforeDestroy () {
    window.removeEventListener("popstate", this.boundPopState) 
  },
  methods: {
    onPopState (...args) {
      this.$emit("popstate", ...args)
    }
  }
})

router-view 實現:

<template>
  <component :is="routeView" />
</template>
 
<script>
import utils from "~/utils.js"
export default {
  data () {
    return {
      routeView: null
    }
  },
  created () {
    this.boundPopState = this.onPopState.bind(this)
  },
  beforeMount () {
    this.$root.$on("popstate", this.boundPopState)
  },
  beforeDestroy() {
    this.$root.$off("popstate", this.boundPopState)
  },
  methods: {
    onPopState (e) {
      const path = utils.extractUrlPath(window.location.href)
      this.routeView = this.$root.$routes[path] || null
      console.log("[Vue] popstate:", path)
    }
  }
}
</script>

router-link 實現:

<template>
  <a @click.prevent="onClick" href=""><slot></slot></a>
</template>
 
<script>
export default {
  props: {
    to: String
  },
  methods: {
    onClick () {
      history.pushState(null, "", this.to)
      this.$root.$emit("popstate")
    }
  }
}
</script>

小結

前端路由的核心實現原理很簡單,但是結合具體框架后,框架增加了很多特性,如動態路由、路由參數、路由動畫等等,這些導致路由實現變的復雜。本文去粗取精只針對前端路由最核心部分的實現進行分析,并基于 hash 和 history 兩種模式,分別提供原生JS/React/Vue 三種實現,共計六個實現版本供參考,希望對你有所幫助。

所有的示例的代碼放在 Github 倉庫:https://github.com/whinc/web-router-principle

參考

詳解單頁面路由的幾種實現原理

單頁面應用路由實現原理:以 React-Router 為例

到此這篇關于react實現瀏覽器自動刷新的示例代碼的文章就介紹到這了,更多相關react 瀏覽器自動刷新內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://blog.csdn.net/weixin_32129187/article/details/112399624

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产成人精品一区二区三区视频 | 日本中文字幕久久 | 亚洲精品成人av久久 | 久久久影院| 日韩欧美精品 | 激情一区| 免费三级黄色 | 成人动慢 | 国产福利电影 | 91精品综合久久久久久五月天 | 一区二区三区入口 | 亚洲日本va中文字幕 | 欧美精品网| 国产精品成人在线视频 | 99久久免费视频在线观看 | 亚洲国产精品无卡做爰天天 | 国产精品色婷婷亚洲综合看 | av免费网站 | 免费在线a | 在线国产一区 | 天天操操 | 成人免费视频网站在线看 | 久久综合久久综合久久 | 欧美日韩成人在线播放 | 一级毛片免费观看 | 黄视频免费观看网站 | 久久久久无码国产精品一区 | 国产高清av在线一区二区三区 | 欧美综合在线观看 | 免费无遮挡www小视频 | 日韩成人在线播放 | 日韩中文一区二区 | 国产成人一区二区三区在线观看 | 九九热精品视频在线免费观看 | 成人国产精品久久久 | 欧美日韩一级二级三级 | 中文字幕免费中文 | 色成人亚洲www78ixcom | 欧美日韩电影一区二区三区 | 日韩精品专区 | 中文字幕人成乱码在线观看 |