繁体   English   中英

React 错误“对象作为 React 子项无效(找到:[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 但这有点棘手,我会让你深入研究

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

我也使用了这个: React Hook Warnings for async function in useEffect: useEffect function must return a cleanup ZC1C425268E68385D1AB5074C17A94F1

简而言之,解决方案是使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM