![](/img/trans.png)
[英]Objects are not valid as a React child (found: [object Promise])
[英]React error "Objects are not valid as a React child (found: [object Promise])"
我對 React 很陌生。 我正在嘗試使用新版本的 react-router-dom v6 創建一個私有路由處理程序,因此我需要驗證用戶是否經過身份驗證,以便知道是否返回受保護的路由或將用戶重定向到登錄路線。
import { Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { isLogged } from '../helpers/isLogged';
export const PrivateRoute = async ({children}) => {
// Check if the user is authenticated
const userData = useSelector( store => store.user.object);
const logged = await isLogged(userData);
return logged
? children
: <Navigate to="/login" />;
}
問題是我因此而遇到了一些錯誤,但主要是 object promise 之一。
這是怎么回事? 提前致謝!
You can't declare a component async, because an async function returns a Promise, so when you'll use it won't be a component but a Promise object.
如果您需要執行異步操作,則需要使用 useEffect Hook:
export const PrivateRoute = async ({ children }) => {
const [logged, setlLogged] = useState(false);
useEffect(() => {
isLogged(userData).then((res) => {
setIsUserLogged(res);
});
}, []);
// Check if the user is authenticated
const userData = useSelector((store) => store.user.object);
return logged ? children : <Navigate to="/login" />;
};
你也可以在 useEffect 鈎子中使用 async/await 但這有點棘手,我會讓你深入研究
所以,多虧了雨果才能弄清楚。
簡而言之,解決方案是使用 useEffect 並在內部使用異步 function ,並且在運行時,您可以選擇渲染其他任何東西,在我的情況下是“等待......”。
import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { isLogged } from '../helpers/isLogged';
export const PrivateRoute = ({children}) => {
const userData = useSelector((store) => store.user.object);
const [logged, setLogged] = useState(false);
const [checking, setChecking] = useState(true);
useEffect(() => {
const checkAuth = async () => {
// Check if the user is authenticated
isLogged(userData).then((res) => {
setLogged(res);
// sets checking variable in false so the component can be rendered.
setChecking(false);
});
}
checkAuth();
}, [userData]);
if(checking){
// Renders 'wait' until isLogged is resolved with the data.
return (<h1>Wait...</h1>);
}
return logged ? children : <Navigate to="/login" />
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.