React.js 如何在组件内循环和渲染组件?

React.js How to loop and render component inside component?

我正在尝试根据数据列表渲染组件。数据列表包括地址和记录的列表,在每个地址记录中,它包含一个或多个成员记录。 数据结构如下所示:

combineData:[
addressData:{addressNo:... },
 memberDataList:[{...}]  
]

我想这样渲染:

<address1>
<member1 of address 1>
<member2 of address 1>
<address2>
<member1 of address 2>
<member2 of address 2>
<member3 of address 2>
......
 
class AddressMembersTable extends React.Component {
    addressMembersViews = () => this.props.combineData.map((combineData, index) => {
        return (
            <Container layout="vbox">
                <AddressField
                    ref={'addressField'}
                    key={'addressField'}
                    addressData={combineData.addressData}
                />
  {combineData.memberDataList.forEach((memberData,index)=>{
               return(
                    <MemberField
                    ref={'memberField_' + index}
                   memberData = {combineData.memberDataList}
                   />
               )
        })}
        </Container>
        )

})}

我试图为 MemberField 组件循环 memberDataList,但只有 AddressField 能够显示。我怎样才能正确渲染组件?

您将按照您的方式映射它 this.props.combineDataArray.prototype.forEach is a void return。您需要 return 您映射到的 JSX 数组。

{combineData.memberDataList.map((memberData, index) => (
  <MemberField
    key={index}
    ref={'memberField_' + index}
    memberData = {combineData.memberDataList}
  />
))}

您使用了错误的列表功能。

map - 转换列表

forEach - 对每个列表项执行副作用

const list = [1, 2, 3]
const double = n => n * 2

const a = list.map(double)
console.log(a) // [2, 4, 6]

const b = list.forEach(double)
console.log(b) // undefined