首页 > 解决方案 > React-Native 如何从 props 传递和访问数组数组中的数据

问题描述

我正在尝试: 1)创建一个对象数组,其中一个对象是另一个对象数组 2)我想将数据从父组件(创建的数组)传递给子组件以呈现数组内的数据

以下是我创建数组的父组件 dealList.js:

constructor(){
const array = [
            {
                title: 'Picture Max ',
                dealId: 12345,
                publishDate: '14 Sept',
                status: 'Good',
                position: 'Manager',
                sub_Category: [{
                    firstTime: '6:00pm',
                    tableTitle: 'Guidance',
                    company: 'Capcom',
                    tableDetails: [
                        [
                            '53',
                            'CT5+Area',
                            'Benchmarking'
                        ],
                        [
                            'afa445',
                            '3mL 3fmjer',
                            '300'
                        ],
                        [
                            '7Y',
                            '4.3 - 434 Area',
                            '200'
                        ],

                    ]

                }]

 this.state = {

            AccordionData: [...array]


        };

}

//Passing array as props to child component function 
renderDealBoards() {

        return (
            this.state.AccordionData.map((item, key) =>

                (
                    <DBDetails key={item.title} 
                                      item={item}/>

                ))
        );
}

以下是我的子组件 DBDetails.js

this.props.item.tableDetails.map((item, key) => (

       <Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
           <Row data={this.state.tbHead} style={styles.tbHead}                       textStyle={styles.tbText}/>
 <Rows data={item} textStyle={styles.tbText}/>
      </Table>
           ))

但是,当我运行代码时,会出现以下错误代码:

TypeError: TypeError: Cannot read property 'map' of undefined

任何人都可以帮助我解决问题以及我如何克服这个问题,因为我是 react-native 的新手并且最近刚刚编码。

标签: arraysreact-nativestatereact-props

解决方案


问题是您指的是 this.props.item.tableDetails.map 但您的 tableDetails 位于 sub_Category 属性内,该属性也是一个数组。所以你应该使用 sub_Category.map(x=>x.tableDetails.map(//somecode here)) 来映射 sub_Category 内的 itableDetails。


推荐阅读