[英]Using Flow typing with the map function
Here's some simple React layout code:下面是一些简单的 React 布局代码:
<div>
{users.map(user => <AddUser user={user} key={user.id} />)}
</div>
I'm simply calling N instances of an AddUser
component and passing it some values.我只是调用
AddUser
组件的 N 个实例并传递给它一些值。 Here's how the User
object is defined:以下是
User
object 的定义方式:
export type User = {
id: number,
email: string,
role: string,
firstName: string,
lastName: string
}
Over the {user}
instance I'm getting this error:在
{user}
实例上,我收到此错误:
Cannot create
AddUser
element because null or undefined [1] is incompatible withUser
[2] in propertyuser
.无法创建
AddUser
元素,因为 null 或 undefined [1] 与属性user
中的User
[2] 不兼容。 and over theid
property of{user.id}
I'm getting this error: Cannot getuser.id
because propertyid
is missing in null or undefined [1].在
{user.id}
的id
属性上,我收到此错误:Cannot getuser.id
because propertyid
is missing in null or undefined [1]。
How should I correct this?我应该如何纠正这个?
UPDATE:更新:
In the interest of completeness, here's the working solution of the code proposed by @Mike Abeln:为了完整起见,这是@Mike Abeln 提出的代码的工作解决方案:
<div>
{users.map(user => {
return (user !== undefined && user !== null)
? <AddUser user={user} key={user.id} classes={classes} state={fleetCustomerState} dispatch={dispatch} />
: null
})}
</div>
what flow
is telling you here is that you should check to make sure that <AddUser />
is not null
or undefined
这里的
flow
告诉您的是,您应该检查以确保<AddUser />
不是null
或undefined
Return the AddUser
component after checking against null
and undefined
:在检查
null
和undefined
后返回AddUser
组件:
<div>
{users.map(user => {
return (user !== undefined && user !== null) ? <AddUser user={user} key={user.id} /> : null
})}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.