[英]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.