【问题标题】:React - redirect and render component with props with react routerReact - 使用 React 路由器重定向和渲染组件
【发布时间】: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('/') 并返回 &lt;Home message={true}/&gt; 但这不起作用,因为没有传递道具。

有没有办法将两者结合起来?还是我错过了一些额外的步骤?

【问题讨论】:

    标签: javascript reactjs react-router browser-history


    【解决方案1】:

    history.push('/') 之后的代码导致错误,因为 isauthenticated 为 false,则用户对象不包含这些字段,因此出现错误!

    import React from 'react';
    import {useAuth0} from '@auth0/auth0-react';
    
    export const Profile = ({history}) => {
      const {user, isAuthenticated} = useAuth0();
    
      if(!isAuthenticated) {
         history.push('/');
         return
      }
    
      else{ 
        const {email, picture} = user;
    
        return (
          <div>
            <h4>Profile</h4>
            <p>{email}</p>
            <p>{picture}</p>
          </div>
        );
      }
    }; 
    

    这应该可行!

    【讨论】:

    • 函数仅在遇到返回或函数块结束后才返回!
    • 谢谢!是否可以在将用户重定向到“/”的同时将道具发送到另一个组件?
    • 如果对您有帮助,请采纳答案,将问题标记为已回答!如果还有任何疑问,您可以随时提问!
    猜你喜欢
    • 2020-03-04
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多