我们有大量的条件逻辑,只要存在数据就只需要显示一些内容。因此,很多逻辑看起来像这样(简化版):
{
users
&&
<span>{user.length}</span>
}
因此,我创建了一个仅在prop评估为true时才渲染子代的组件,如下所示:
const If = ({truthy, children}) => (
truthy ? <>{children}</> : null
)
实际上看起来像这样:
<If truthy={users}>
{users.length}
</If>
但是,这是行不通的,我无法一生找出原因。
如果未定义用户,我将得到Cannot read property 'length' of undefined
,这意味着首先要评估孩子。那应该在React中发生吗?我有什么办法可以解决这个问题?
答案 0 :(得分:2)
这里的问题是无论如何都要评估内容(在这种情况下为children
,所以当您要访问可能是null
/ { {1}}。
我写了similar library,但它也缺少此功能。
答案 1 :(得分:1)
我只想补充一点,您可以使用渲染道具来解决此问题:
<If truthy={users}>
{(users) => users.length}
</If>
和
const If = ({truthy, children}) => (
truthy ? <>{children(truthy)}</> : null
)
但这值得吗?
答案 2 :(得分:0)
这不可能像Sagiv解释的那样,但是您可以使用renderProps模拟它:
const If = ({truthy, children}) => (
truthy ? children(truthy) : null
);
<If truthy={users}>
{
(truthy)=>truthy.length
}
</If>