为什么在_app.js中添加window.location.href呢?



我想进行身份验证。如果用户没有登录,它将被重定向到登录页面。我在Provider文件中添加了这个条件,并在_app.js中实现了它。在我添加了这个文件之后:

const reds = () => {
if(typeof window !== 'undefined'){
if(!user){
window.location.href = '/login'
}else if(pathname === '/login' && user){
window.location.href = '/'
}else{
window.location.href = '/'
}
}
}

网页总是会重新加载。我该如何解决这个问题?如何使auth重定向在接下来的js正确?完整代码在

下面
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'
import configureStore from '../store'
const { store, persistor } = configureStore()
const AuthProvider = props => {
console.log("fasdfasd")
const [user, setUser] = useState(true)
const { pathname, events } = useRouter()
const router = useRouter()
const handleRouteChange = url => {
if(!user){
window.location.href = '/login'
}else if(pathname === '/login' && user){
window.location.href = '/'
}else{
window.location.href = '/'
}
}
const reds = () => {
if(typeof window !== 'undefined'){
if(!user){
window.location.href = '/login'
}else if(pathname === '/login' && user){
window.location.href = '/'
}else{
window.location.href = '/'
}
}
}
useEffect(() => {
reds()
},[pathname])
useEffect(() => {
events.on('routeChangeStart', handleRouteChange)
return () => {
events.off('routeChangeStart', handleRouteChange)
}
},[user])
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
{ props.children }
</PersistGate>
</Provider>
)
}
export default AuthProvider

reload是windows.loaction.href的默认行为。使用router.push("/login")

最新更新