【发布时间】:2020-07-09 04:47:55
【问题描述】:
我正在使用挂钩来保护我的路线。我遇到的问题是检查用户身份验证状态的调用返回一个 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'}}/>
}
【问题讨论】:
标签: reactjs react-router amazon-cognito react-router-dom aws-amplify