繁体   English   中英

对象无效,无法作为React子对象(找到:[object Promise])

[英]Objects not valid as a React child (found: [object Promise])

我有一个渲染路径的私有路由组件,它返回Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise])当我使用async/await调用方法时, Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]) 我需要更改什么? 有一个checkTokenExpirationMiddlewareAdvertiser()可以验证用户的角色并呈现正确的仪表板。 似乎当我async/await用户时,诺言无法完全解决。

我试图从函数中删除async ,但后来我无法从函数中获取返回值。

const AdvertiserPrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      console.log(rest)
      if (!loggedInUser())
        return (
          <Redirect
            to={{ pathname: '/login', state: { from: props.location } }}
          />
        );
      return checkTokenExpirationMiddlewareAdvertiser(
        () => <Component {...props} />, // success component
        () => <AdvertiserError />, // failure component
      );
    }}
  />
);
export const checkTokenExpirationMiddlewareAdvertiser = async (success, fail) => {
  const { user } = await loggedInUser();
  console.log(user)
  if (user) {
    const { token } = user;
    if (jwtDecode(token).exp < Date.now() / 1000) {
      removeUser();
      return fail();
    }
    if (user.role !== 'advertiser') return fail();
    console.log('here');
    return success();
  }
  console.log("here")
  return fail();
};

loggedInUser()结合使用的async await不一致。

  1. 可以将其从checkTokenExpirationMiddlewareAdvertiser删除
  2. 或将其添加到AdvertiserPrivateRoute (请参见下文)

取决于loggedInUser()是否为异步函数

const AdvertiserPrivateRoute = async ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      console.log(rest)
      const userLoggedIn = await loggedInUser();
      if (!userLoggedIn)
        return (
          <Redirect
            to={{ pathname: '/login', state: { from: props.location } }}
          />
        );
      return checkTokenExpirationMiddlewareAdvertiser(
        () => <Component {...props} />, // success component
        () => <AdvertiserError />, // failure component
      );
    }}
  />
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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