【发布时间】:2020-11-25 23:47:54
【问题描述】:
我有一个functional component 个人资料,我只希望用户通过身份验证访问它,如果没有,他们应该被重定向。
import React from 'react';
import {useAuth0} from '@auth0/auth0-react';
export const Profile = ({history}) => {
const {user, isAuthenticated} = useAuth0();
if (!isAuthenticated) history.push('/');
const {email, picture} = user;
return (
<div>
<h4>Profile</h4>
<p>{email}</p>
<p>{picture}</p>
</div>
);
};
如果我尝试直接访问 /profile 会出现错误。
`TypeError: Cannot destructure property 'email' of 'user' as it is` undefined.
我想做的是:
- 如果用户未通过身份验证,则呈现
Home组件并传递一个 props 布尔值。 - 将应用重定向到
'/'
我正在尝试合并 history.push('/') 并返回 <Home message={true}/> 但这不起作用,因为没有传递道具。
有没有办法将两者结合起来?还是我错过了一些额外的步骤?
【问题讨论】:
标签: javascript reactjs react-router browser-history