如何用承诺创建受保护的路线

时间:2020-07-09 04:47:55

标签: reactjs react-router amazon-cognito react-router-dom aws-amplify

我正在使用挂钩保护我的路线。我遇到的问题是,用于检查用户的身份验证状态的调用返回了Promise,因此该挂钩返回默认值a,然后身份验证状态不再有用,因为我们已经重定向了。

那么我该如何等待从挂钩返回,直到完成身份验证检查?这是我的代码:

export function ProtectedRoute(props){

const [loggedIn, setLoggedIn] = useState(false);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
    async function fetchUser() {
        let user = null;

        try {
            user = await Auth.currentAuthenticatedUser()
            if (user) {
                setLoggedIn(true);
            } else
            {
                setLoggedIn(false);
            }
        } catch (e) {
            setLoggedIn(false);
        }
    }
    fetchUser()
});

console.log("ProtectedRoute: returning " + loggedIn);
if (loggedIn)
    return props.component
else
    return <Redirect to={{pathname: '/login'}}/>

}

2 个答案:

答案 0 :(得分:0)

我将添加一个新状态loading,直到ist true,仅渲染一个加载组件:

    export default ProtectedRoute(props) {
    
      const [loggedIn, setLoggedIn] = useState(false);
      const [loading, setLoading] = useState(true);
      
      useEffect(() => {
        (async () => {
          try {
            setLoading(true);
            const user = await Auth.currentAuthenticatedUser();
            setLoggedIn(!!user);
          } catch (error) {
            console.log(error);
            setLoggedIn(false);
          } finally {
            setLoading(false);
          }
        })();
      }, []);
    
      if(loading) return <h1>Loading...</h1>;
        
      if (loggedIn) return props.component
    
      return <Redirect to={{ pathname: '/login' }}/>
  }

答案 1 :(得分:0)

找到了一个解决方案...对于isAuthenticated,必须默认为'true',然后进行重定向(如果不是这种情况,则重定向(在我的初始代码中似乎对我来说是违反逻辑的))

import socket

adapter_addr = 'e4:a4:71:63:e1:69'
port = 3  # Normal port for rfcomm?
buf_size = 1024

s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((adapter_addr, port))
s.listen(1)
try:
    print('Listening for connection...')
    client, address = s.accept()
    print(f'Connected to {address}')

    while True:
        data = client.recv(buf_size)
        if data:
            print(data)
except Exception as e:
    print(f'Something went wrong: {e}')
    client.close()
    s.close()

}