I've added some piece of code in render method of react using conditional (ternary) operator. The thing is the condition is rendered true also the control goes into the block. But when I print the value the variable is undefined
I tried inserting an alert inside the block to check if the control traverses the block and it worked.
const comments =
details.comments_count >= 1
? Object.keys(details.comments_list).forEach(keys => {
return (
<ListItem
alignItems="flex-start"
key={details.comments_list[keys].aid}
>
<ListItemAvatar>
<Avatar>{details.comments_list[keys].aname.charAt(0)}</Avatar>
</ListItemAvatar>
<Card style={useStyles.card}>
<CardContent>
<ListItemText
primary={details.comments_list[keys].aname}
secondary={details.comments_list[keys].content}
/>
</CardContent>
</Card>
</ListItem>
);
})
: null;
console.log(comments);
//=>undefined
I don't actually know why this this is happening, given the result of conditional expression is true
. Any help is appreciated. Thanks.
forEach
won't return anything but undefined
. You need to use map
.
const comments =
details.comments_count >= 1
? Object.keys(details.comments_list).map(keys => {
return (
<ListItem
alignItems="flex-start"
key={details.comments_list[keys].aid}
>
<ListItemAvatar>
<Avatar>{details.comments_list[keys].aname.charAt(0)}</Avatar>
</ListItemAvatar>
<Card style={useStyles.card}>
<CardContent>
<ListItemText
primary={details.comments_list[keys].aname}
secondary={details.comments_list[keys].content}
/>
</CardContent>
</Card>
</ListItem>
);
})
: null;
console.log(comments);
Exactly how @ravibagul91 says. ForEach is void function check this for details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.