我们有时候会遇到这种业务场景: 进入某个页面时,我们需要验证用户是否已经登陆,是否拥有足够权限?我们可以通过监听路由的变化来实现。但是在react下,怎么实现呢?
下面讨论实现过程:
- 手动实现
- react-router-watcher实现, 详细请见示例代码
手动实现
使用Hook方式实现:
import {
useEffect, useState, useRef, useCallback, useMemo } from 'react'
import {
useLocation, useHistory, useRouteMatch } from 'react-router'
const useWatcher = () => {
const location = useLocation()
const history = useHistory()
const match = useRouteMatch()
const [pathname, setPathname] = useState('')
const listeners = useRef([])
const addListener = useCallback((listener) => {
listeners.current.push(listener)
}, [])
const removeListener = useCallback((listener) => {
const index = listeners.current.findIndex(item => item === listener)
if (index >= 0) {
listeners.current.splice(index, 1)
}
}, [])
const execListeners = useCallback(() => {
listeners.current.forEach(func => {
func({
history,
match,
location
})
})
}, [history, match, location])
useEffect(() => {
if (pathname !== location.pathname) {
execListeners()
setPathname(pathname)
}
}, [location, execListeners, pathname])
const watcher = useMemo(() => {
return {
removeListener, addListener
}
}, [removeListener, addListener])
return watcher
}
export default useWatcher
使用react类实现:
import React, {
Component } from 'react'
import {
withRouter