Reactjs useEffect正在进入一个循环

Reactjs useEffect正在进入一个循环,reactjs,use-effect,authprovider,Reactjs,Use Effect,Authprovider,我试图在app.js中实现一个简单的保护路由中间件。 如果用户已通过身份验证,则无法转到“/登录”和“/”。我还在app.js中做了一个简单的函数,检查用户是否未通过身份验证。如果他未通过身份验证,他将从“/主页”重定向到“/登录”。不幸的是,如果我这样做,我的网站不会停止刷新。 例如:如果未通过身份验证,并且我试图访问“/主页”,我将被重定向到“/登录”,但随后进入刷新循环!:( app.js function App() { const authenticated = useSelect

我试图在app.js中实现一个简单的保护路由中间件。 如果用户已通过身份验证,则无法转到“/登录”和“/”。我还在app.js中做了一个简单的函数,检查用户是否未通过身份验证。如果他未通过身份验证,他将从“/主页”重定向到“/登录”。不幸的是,如果我这样做,我的网站不会停止刷新。 例如:如果未通过身份验证,并且我试图访问“/主页”,我将被重定向到“/登录”,但随后进入刷新循环!:(

app.js

function App() {
  const authenticated = useSelector((state) => state.user.authenticated)
  const dispatch = useDispatch()

useEffect(() => {
   if (!authenticated) {
    window.location.href = '/login'
  } 
  }, [
    // I tried every possible combination
  ])

  

  return (
    <div>
      <Router>
        <Switch>
          <Route exact path='/home' component={HomePage} />
          <ProtectedRoute exact path='/login' component={LoginPage} />
          <ProtectedRoute exact path='/' component={LoginPage} />

         
        </Switch>
      </Router>
    </div>
  )
}
函数应用程序(){
const authenticated=useSelector((state)=>state.user.authenticated)
const dispatch=usedpatch()
useffect(()=>{
如果(!已验证){
window.location.href='/login'
} 
}, [
//我尝试了所有可能的组合
])
返回(
)
}
ProtectedToute.js

import React from 'react'
import { useSelector } from 'react-redux'
import { Route, Redirect } from 'react-router-dom'

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const authenticated = useSelector((state) => state.user.authenticated)
  console.log('Route', authenticated)
  return (
    <Route
      {...rest}
      render={(props) => {
        if (authenticated) {
          return <Redirect to='/home' />
         
        } else {
          return (
        
            <Component {...props} />
          )
        }
      }}
    />
  )
}

export default ProtectedRoute
从“React”导入React
从“react redux”导入{useSelector}
从“react router dom”导入{Route,Redirect}
const ProtectedRoute=({component:component,…rest})=>{
const authenticated=useSelector((state)=>state.user.authenticated)
console.log('Route',已验证)
返回(
{
如果(已验证){
返回
}否则{
返回(
)
}
}}
/>
)
}
导出默认的ProtectedRoute

您是否尝试使用历史对象?TypeError:无法读取未定义的属性“push”是执行历史记录时的错误。push(“/”)您需要使用来自react router的useHistory挂钩,它返回历史记录
const history=useHistory()
从“react router dom”导入{useHistory}const history=useEffect()=>{if(!authenticated){history.push('/')},[])。相同的错误:(I)如果我在homepage.js中这样做,我只是感到困惑