【问题标题】:React error "Objects are not valid as a React child (found: [object Promise])"React 错误“对象作为 React 子项无效(找到:[object Promise])”
【发布时间】:2025-11-27 19:40:01
【问题描述】:

我对 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" />;
}

问题是我因此遇到了一些错误,但主要是对象承诺错误。

发生了什么事?提前致谢!

【问题讨论】:

  • 试试&lt;&gt;{children}&lt;/&gt;。虽然不确定
  • 检查孩子道具的组件。那里可能存在一些错误。

标签: javascript reactjs async-await react-router


【解决方案1】:

你不能声明一个组件异步,因为一个异步函数返回一个 Promise,所以当你使用它时它不会是一个组件而是一个 Promise 对象。

如果你需要做一个异步操作,你需要使用 useEffect Hook :

  export const PrivateRoute = ({ 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,但它有点棘手,我会让你深入研究

【讨论】:

    【解决方案2】:

    所以,多亏了 Hugo 才能弄清楚。

    我也用过这个: React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

    简而言之,解决方案是使用 useEffect 并在内部使用异步函数,并且在运行时,您可以选择渲染其他任何内容,在我的情况下是“等待...”。

    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" />
    }
    

    【讨论】:

      最近更新 更多