这篇文章给大家分享的是有关react如何实现浏览器自动刷新的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
路由的概念来源于服务端,在服务端中路由描述的是 URL 与处理函数之间的映射关系。
在 Web 前端单页应用 SPA(Single Page Application)中,路由描述的是 URL 与 UI 之间的映射关系,这种映射是单向的,即 URL 变化引起 UI 更新(无需刷新页面)。
要实现前端路由,需要解决两个核心问题:
如何改变 URL 却不引起页面刷新?如何检测 URL 变化了?
下面分别使用 hash 和 history 两种实现方式回答上面的两个核心问题。
hash 是 URL 中 hash (#
) 及后面的那部分,常用作锚点在页面内进行导航,改变 URL 中的 hash 部分不会引起页面刷新
通过 hashchange 事件监听 URL 的变化,改变 URL 的方式只有这几种:通过浏览器前进后退改变 URL、通过标签改变 URL、通过wind
ow.location改变URL,这几种情况改变 URL 都会触发 hashchange 事件
history 提供了 pushState 和 replaceState 两个方法,这两个方法改变 URL 的 path 部分不会引起页面刷新
history 提供类似 hashchange 事件的 popstate 事件,但 popstate 事件有些不同:通过浏览器前进后退改变 URL 时会触发 popstate 事件,通过pushState/replaceState
或标签改变 URL 不会触发 popstate 事件。好在我们可以拦截 pushState/r
eplaceState的调用和标签的点击事件来检测 URL 变化,所以监听 URL 变化可以实现,只是没有 hashchange 那么方便。
基于上节讨论的两种实现方式,分别实现 hash 版本和 history 版本的路由,示例使用原生 HTML/JS 实现,不依赖任何框架。
运行效果:
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
}
}
运行效果:
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-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 实现
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} />;
运行效果:
使用方式和 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 实现
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-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: '<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 实现:
<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>
运行效果:
使用方式和 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 实现:
<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>
感谢各位的阅读!关于“react如何实现浏览器自动刷新”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。