如何修复 React 中的对象作为 React 子对象无效(找到:带有键 {} 的对象)

问题描述 投票:0回答:2

我对反应还很陌生,我正在构建一个网站,如果我的用户没有足够的范围来访问它,我想将页面保持私有。我有以下代码:

更新:我尝试仅设置 setCanAccess(true) ,但仍然收到错误。当我完全注释掉该行时,没有错误。我也尝试将其设置在 .then() 回调之外,但仍然收到错误。

function ProtectedPage(props, children) {
    var [canAccess, setCanAccess] = useState(false);

    useEffect(() => {
        LoginManager.getStoredUser().then(user => {
            setCanAccess(user.scopes.includes(props.scope));
        });
    }, [props.scope]);

    return (
        <>
            {canAccess ? (
                <>{children}</>
            ) : (
                <>
                    <Spacer height="150px" />
                    <p>
                        You need to be logged in with the proper permissions to
                        view this page. Here is the scope: {props.scope}.
                    </p>
                    <Link to="/login">Log In</Link>
                </>
            )}
        </>
    );
}

function Secret() {
    return (
        <ProtectedPage scope="owner">
            <PageHeader>Secret Page</PageHeader>
        </ProtectedPage>
    );
}

我不断收到以下错误:

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
感谢任何帮助,我已经尝试解决这个问题几个小时了,但没有任何意义了哈哈。

谢谢:)

javascript reactjs
2个回答
0
投票

你正在渲染 {children} ,它本身就是一个对象,当我们直接渲染一个对象时,它总是会给我们这个错误。


0
投票

那么你应该阅读文档。组件 props 中有

children
,因此您应该将
children
作为
props.children
访问,并从
ProtectedPage
组件中删除第二个参数。

<>{props.children}</>

这应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.