猿问

如何修复对象作为 React 子对象承诺无效

我使用 react 创建了一个电子学习应用程序,并希望将路线拆分给许多用户(学生、教师和管理员),因此我使用了这种方法


新路由.js


const NewRoute = ({

    component: Component,

    type: type,

    ...rest

}) => (

    <Route

        {...rest}

        render={ async props => {

            console.log(await CT.checkType(type));

            return CT.checkType(type) === false ? (

                <Redirect to='/login' />

            ) : (

                <Component {...props} />

            )

        }

        }

    />

);

检查类型.js


export default {

  checkType: async (type) => {

    try{

      const res = await axios.get('/api/check/');

      console.log('api response',res);

      return true

    } catch(err) {

      console.error(err.message);

      return false

    }

  }

}

未捕获的错误:对象作为 React 子对象无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。


达令说
浏览 138回答 1
1回答

墨色风雨

未捕获的错误:对象作为 React 子对象无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组您收到此错误是因为您将异步函数传递给render,它是一个Promise对象。您需要传递一个 React 组件。这意味着此检查CT.checkType(type) === false不能是异步调用。所以你试图做的事情是不可能的。如果你想根据请求渲染一个组件,你需要的地方是什么。您需要声明检查以下内容:检查它是否正在加载检查它是否有效所以你首先设置路由正在加载(渲染一些加载组件)。承诺完成后,您设置正在加载为 false 并设置它是否有效,它将返回Redirector&nbsp;Component。我为这种情况做了一个非常简单的要点,但逻辑是这样的:const PrivateRoute = ({ component: Component, ...otherProps }) => {&nbsp; &nbsp; const { isAuthenticated, isLoading } = useContext(AuthContext)&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Route&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {...otherProps}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; render={props => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; !isLoading&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isAuthenticated&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Component {...props} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Redirect to={otherProps.redirectTo ? otherProps.redirectTo : '/signin'} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Loading />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; )}在AuthContext它内部调用一个方法,该方法设置isAuthenticated并isLoading基于异步请求。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答