簡體   English   中英

React - 使用 React 路由器重定向和渲染組件

[英]React - redirect and render component with props with react router

我有一個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組件並傳遞道具 boolean。
  • 將應用程序重定向到'/'

我正在嘗試結合history.push('/')並返回<Home message={true}/>但這不起作用,因為沒有傳遞道具。

有沒有辦法將兩者結合起來? 還是我錯過了一些額外的步驟?

history.push('/')之后的代碼導致錯誤,因為isauthenticated為假,然后用戶 object 不包含這些字段,因此錯誤!

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>
    );
  }
}; 

這應該工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM