我对反应还很陌生,我正在构建一个网站,如果我的用户没有足够的范围来访问它,我想将页面保持私有。我有以下代码:
更新:我尝试仅设置 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.
感谢任何帮助,我已经尝试解决这个问题几个小时了,但没有任何意义了哈哈。
谢谢:)
你正在渲染 {children} ,它本身就是一个对象,当我们直接渲染一个对象时,它总是会给我们这个错误。
那么你应该阅读文档。组件 props 中有
children
,因此您应该将 children
作为 props.children
访问,并从 ProtectedPage
组件中删除第二个参数。
<>{props.children}</>
这应该有效。