簡體   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