溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

發(fā)布時(shí)間:2021-04-23 13:55:54 來(lái)源:億速云 閱讀:403 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

什么是前端路由?

路由的概念來(lái)源于服務(wù)端,在服務(wù)端中路由描述的是 URL 與處理函數(shù)之間的映射關(guān)系。

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

如何實(shí)現(xiàn)前端路由?

要實(shí)現(xiàn)前端路由,需要解決兩個(gè)核心問(wèn)題:

如何改變 URL 卻不引起頁(yè)面刷新?如何檢測(cè) URL 變化了?

下面分別使用 hash 和 history 兩種實(shí)現(xiàn)方式回答上面的兩個(gè)核心問(wèn)題。

hash 實(shí)現(xiàn)

  • hash 是 URL 中 hash (#) 及后面的那部分,常用作錨點(diǎn)在頁(yè)面內(nèi)進(jìn)行導(dǎo)航,改變 URL 中的 hash 部分不會(huì)引起頁(yè)面刷新

  • 通過(guò) hashchange 事件監(jiān)聽 URL 的變化,改變 URL 的方式只有這幾種:通過(guò)瀏覽器前進(jìn)后退改變 URL、通過(guò)標(biāo)簽改變 URL、通過(guò)window.location改變URL,這幾種情況改變 URL 都會(huì)觸發(fā) hashchange 事件

history 實(shí)現(xiàn)

  • history 提供了 pushState 和 replaceState 兩個(gè)方法,這兩個(gè)方法改變 URL 的 path 部分不會(huì)引起頁(yè)面刷新

  • history 提供類似 hashchange 事件的 popstate 事件,但 popstate 事件有些不同:通過(guò)瀏覽器前進(jìn)后退改變 URL 時(shí)會(huì)觸發(fā) popstate 事件,通過(guò)pushState/replaceState或標(biāo)簽改變 URL 不會(huì)觸發(fā) popstate 事件。好在我們可以攔截 pushState/replaceState的調(diào)用和標(biāo)簽的點(diǎn)擊事件來(lái)檢測(cè) URL 變化,所以監(jiān)聽 URL 變化可以實(shí)現(xiàn),只是沒(méi)有 hashchange 那么方便。

 原生JS版前端路由實(shí)現(xiàn)

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

基于 hash 實(shí)現(xiàn)

運(yùn)行效果:

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

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="">    <!-- 渲染路由對(duì)應(yīng)的 UI -->
    <div id="routeView"></div>
  </ul>
</body>

JavaScript 部分:

// 頁(yè)面加載完不會(huì)觸發(fā) hashchange,這里主動(dòng)觸發(fā)一次 hashchange 事件
window.addEventListener('DOMContentLoaded', onLoad)
// 監(jiān)聽路由變化
window.addEventListener('hashchange', onHashChange)
 
// 路由視圖
var routerView = null
 
function onLoad () {
  routerView = document.querySelector('#routeView')
  onHashChange()
}
 
// 路由變化時(shí),根據(jù)路由渲染對(duì)應(yīng) UI
function onHashChange () {
  switch (location.hash) {
    case '#/home':
      routerView.innerHTML = 'Home'
      return
    case '#/about':
      routerView.innerHTML = 'About'
      return
    default:
      return
  }
}

基于 history 實(shí)現(xiàn)

運(yùn)行效果:

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

HTML 部分:

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

JavaScript 部分:

// 頁(yè)面加載完不會(huì)觸發(fā) hashchange,這里主動(dòng)觸發(fā)一次 hashchange 事件
window.addEventListener('DOMContentLoaded', onLoad)
// 監(jiān)聽路由變化
window.addEventListener('popstate', onPopState)
 
// 路由視圖
var routerView = null
 
function onLoad () {
  routerView = document.querySelector('#routeView')
  onPopState()
 
 href="">  // 攔截 <a> 標(biāo)簽點(diǎn)擊事件默認(rèn)行為, 點(diǎn)擊時(shí)使用 pushState 修改 URL并更新手動(dòng) UI,從而實(shí)現(xiàn)點(diǎn)擊鏈接更新 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()
  }))
}
 
// 路由變化時(shí),根據(jù)路由渲染對(duì)應(yīng) UI
function onPopState () {
  switch (location.pathname) {
    case '/home':
      routerView.innerHTML = 'Home'
      return
    case '/about':
      routerView.innerHTML = 'About'
      return
    default:
      return
  }
}

React 版前端路由實(shí)現(xiàn)

基于 hash 實(shí)現(xiàn)

運(yùn)行效果:

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

使用方式和 react-router 類似:

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

BrowserRouter 實(shí)現(xiàn)

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 實(shí)現(xiàn)

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

Link 實(shí)現(xiàn)

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

基于 history 實(shí)現(xiàn)

運(yùn)行效果:

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

使用方式和 react-router 類似:

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

HistoryRouter 實(shí)現(xiàn)

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 實(shí)現(xiàn)

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

Link 實(shí)現(xiàn)

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

Vue 版本前端路由實(shí)現(xiàn)

基于 hash 實(shí)現(xiàn)

運(yùn)行效果:

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

使用方式和 vue-router 類似(vue-router 通過(guò)插件機(jī)制注入路由,但是這樣隱藏了實(shí)現(xiàn)細(xì)節(jié),為了保持代碼直觀,這里沒(méi)有使用 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: '<h3>Home</h3>'
  },
  '/about': {
    template: '<h3>About</h3>'
  }
}
 
const app = new Vue({
  el: '.vue.hash',
  components: {
    'router-view': RouterView,
    'router-link': RouterLink
  },
  beforeCreate () {
    this.$routes = routes
  }
})

router-view 實(shí)現(xiàn):

<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 實(shí)現(xiàn):

<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 實(shí)現(xiàn)

運(yùn)行效果:

react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新

使用方式和 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: '<h3>Home</h3>'
  },
  '/about': {
    template: '<h3>About</h3>'
  }
}
 
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 實(shí)現(xiàn):

<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 實(shí)現(xiàn):

<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>

感謝各位的閱讀!關(guān)于“react如何實(shí)現(xiàn)瀏覽器自動(dòng)刷新”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI