如何清理react useEffect钩子中的放大异步Auth函数?

时间:2020-06-30 09:04:22

标签: reactjs amazon-web-services async-await react-hooks aws-amplify

我正在尝试使用react-router的专用路由器组成来对落在受保护路由上的用户进行身份验证。 AWS Amplify auth是用于提供身份验证的选定服务。我已成功设法注册并登录用户。我当前的问题是,当用户着陆在受保护的路线上时,它能够检查当前的用户会话。我可以在useEffect挂钩中注销当前用户会话,但是,在验证会话存在后,将 authenticated 状态设置为 true 似乎会导致问题。我在控制台中不断收到一个错误,由于未取消挂钩中发出的异步请求,该错误不断强调内存泄漏。

所以我现在的问题是,如何取消 useEffect 挂钩中的AWS Amplify auth异步功能请求?

控制台错误

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

private-route.js

import React,{useEffect,useState} from 'react'
import {Route,Redirect} from 'react-router-dom'
import {checkCurrentSession} from '../shared/auth-services'


const PrivateRoute = ({ component: Component, ...rest }) => {

const [authenticated,setAuthenticated]=useState(false);

useEffect( () => {
   async function check(){
       try{
          const response= await checkCurrentSession()
          console.log(response)
          setAuthenticated(true)
       }catch(err){
           console.log(err)
       }
   }
   check();
}, [])


return(
<Route {...rest} render={(props) => (
  authenticated? <Component {...props} />
    : <Redirect to='/user-login' />
)} />
 )}

export default PrivateRoute

auth-services.js

const checkCurrentSession=async()=>{
    return await Auth.currentSession()
    }

0 个答案:

没有答案