[英]react using .map() inside component prop attribute
I'm trying to conditionally render a component based on if that user is online.我正在尝试根据该用户是否在线有条件地呈现组件。 The problem im experiencing is with the
status
prop on my MessengerFriend
component.我遇到的问题是我的
MessengerFriend
组件上的status
道具。 In my conditional statement it is returning both 'online'
and 'offline'
, but when I only use the equivalent if
It returns the online status correctly.在我的条件语句中,它同时返回
'online'
和'offline'
,但是当我只使用等效项时, if
它正确返回在线状态。 My initial thought was that using onlineFriends.map()
is returning both statuses because there are in fact users both online and offline.我最初的想法是使用
onlineFriends.map()
返回两种状态,因为实际上用户在线和离线。
const [friendsList, setFriendsList] = useState([])
const [onlineFriends, setOnlineFriends] = useState([])
let mappedFriendChatList = friendsList.map(friend => {
return(
<MessengerFriend
key={friend.friend_id}
value={friend}
status={onlineFriends.map(onlineFriend => onlineFriend.userId == friend.user_id ? 'online' : 'offline')}
/>
)
})
I'm expecting to have a list of all my friends and there status 'online'
and 'offline'
to display correctly我希望有一个我所有朋友的列表,并且可以正确显示
'online'
和'offline'
Map is the wrong method for this use-case; Map 是这个用例的错误方法;
some
is what you need. some
是你需要的。
{onlineFriends.some(onlineFriend => onlineFriend.userId === friend.user_id) ? 'online' : 'offline'}
You could also use filter
with a length check on the result array, or find
(which would work identically to some
in this case).您还可以使用
filter
对结果数组进行长度检查,或find
(在这种情况下与some
方法的工作方式相同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.