gpt4 book ai didi

javascript - 对象作为 React 子对象无效(发现 : [object Promise])

转载 作者:行者123 更新时间:2023-12-02 23:27:39 26 4
gpt4 key购买 nike

我有一个私有(private)路线组件,可以渲染路线,它返回 Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise])当我使用 async/await 调用方法时。我需要改变什么?有一个checkTokenExpirationMiddlewareAdvertiser()它验证用户的 Angular 色并呈现正确的仪表板。看来当我 async/await对于用户来说, promise 并没有完全解决。

我尝试删除 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();
};

最佳答案

您将 async waitloggedInUser() 结合使用是不一致的。

  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
);
}}
/>
);

关于javascript - 对象作为 React 子对象无效(发现 : [object Promise]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com