React 中如何在非组件的函数中使用history的hooks函数

前言

最近遇到一个问题,针对登陆的token失效时,需要跳转到首页刷新页面。肯定是要跳转到登陆页面让用户重新登陆的,但是React中和Vue不同,跳转依赖于router的hooks函数useHistory.但是在组件中才可以使用history,push()进行跳转,在函数中直接是使用不了的。于是看到这样的解决办法

// utils/history.js
import { createBrowserHistory } from 'history'

// 针对如何在非组件的函数中使用history的hooks函数
export default createBrowserHistory()
// others.js

import history from '@utils/history'

export default function jump() {
    // todo someting
    history.push('xxxxxx')
}

猜你喜欢

转载自blog.csdn.net/u014165391/article/details/128735145