所以我有一些userObject
,具有属性
public userId: string
public displayName: string
public username: string
和具有属性的productObject
public productId: string
public userIds: string[] | null
我正在这样做:
private _$customerUsers: Map<string, UserObject> | undefined = undefined
private _onUsers = (bundle: DataBundleObject<UserObject>) => {
this._$customerUsers = new Map()
for (let customerUser of bundle.listOfData) {
this._$customerUsers.set(customerUser.userId, customerUser)
}
}
我想做
productObject.userIds.map(user => {<span>this._$customerUsers.get(user).username</span>})
我无法按照VScode的说明运行Object is possibly 'undefined'
,所以我尝试了三元运算符:
this._$customerUsers ? this._$customerUsers.get(user) ? this._$customerUsers.get(user).username
,但仍然表示最后一个可能是undefined
。那怎么可能?第二个三元表达式应检查返回对象是否为undefined
。
更新
我可以做到
productObject.userIds.map(user => {
if (this._$customerUsers) {
var userO = this._$customerUsers.get(user)
if (userO === undefined) {<Tag color='red'>N/A</Tag>}
else {
<Tag color="blue" key={user}>{userO.username}</Tag>
}
}
<Tag color='red'>N/A</Tag>
})
但不是
productObject.userIds.map(user => {
if (this._$customerUsers) {
if (this._$customerUsers.get(user) === undefined) {<Tag color='red'>N/A</Tag>}
else {
<Tag color="blue" key={user}>{this._$customerUsers.get(user).username}</Tag>
}
}
<Tag color='red'>N/A</Tag>
})
将其视为变量可以更好地进行评估。
答案 0 :(得分:0)
尝试使用三元运算符使此操作变得困难,通过将变量分配给this._$customerUser.get()
的返回值,效果会更好:
productObject.userIds.map(user => {
if (this._$customerUsers) {
var singleUser = this._$customerUsers.get(user)
if (singleUser === undefined) {<span>N/A</span>}
else {
return <span key={user}>{singleUser.username}</span>
}
}
return <span>N/A</span>
})