简体   繁体   English

Map函数在React组件中返回带有未定义元素的数组

[英]Map function returns array with undefined elements in React component

I currently has a component in which I have passed props into with the following render function: 我目前有一个组件,其中使用以下render函数将道具传递到其中:

 render(){ return ( <Card> <CardHeader>{this.props.title}</CardHeader> <CardBody> <CardSubtitle>Count: {Object.keys(this.props.machines).length}</CardSubtitle> { Object.keys(this.props.machines).length != 0 ? <ListGroup> { console.log('array result: ', Object.keys(this.props.machines).map((machine, key) => { console.log('machine name: ', machine); return <ListGroupItem key={key}> {machine} </ListGroupItem> }) ) } { Object.keys(this.props.machines).map((machine, key) => { console.log('machine name: ', machine); return <ListGroupItem key={key}> {machine} </ListGroupItem> }) } </ListGroup> : null } </CardBody> </Card> ); } 

The problem is that the array returned by the map function contains undefined elements as seen in the console.log('array result: '...) . 问题是map函数返回的数组包含undefined元素,如console.log('array result: '...) However, the console.log('machine name: ', machine) does show individual string elements as shown in the screenshot below: 但是, console.log('machine name: ', machine)确实显示了各个字符串元素,如以下屏幕截图所示:

在此处输入图片说明

I have tried substituting <ListGroupItem> with other tags such as div but to no avail. 我尝试用其他标签(例如div替换<ListGroupItem> ,但无济于事。 Any help will be much appreciated. 任何帮助都感激不尽。

The problem is that while returning from map, your JSX is in the next line to return so while compiling, automatic semicolon is inserted after return in which case it returns undefined, you must either have the JSX element in the same line or use () 问题是,从地图返回时,您的JSX在下一行要返回,因此在编译时,在返回后插入自动分号,在这种情况下它返回未定义,因此您必须在同一行中包含JSX元素或使用()

{
     console.log('array result: ',
     Object.keys(this.props.machines).map((machine, key) => {
           console.log('machine name: ', machine);
           return (    // parenthesis here
                <ListGroupItem key={key}>
                    {machine}
                </ListGroupItem>
            )
     })
}

or 要么

{
     console.log('array result: ',
     Object.keys(this.props.machines).map((machine, key) => {
           console.log('machine name: ', machine);
           return <ListGroupItem key={key}>
                    {machine}
                </ListGroupItem>
     })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM