如何在映射React Native

时间:2018-01-17 04:15:31

标签: react-native

我正在尝试在我的react本机应用程序中映射数组时使用setState。我有一个数组,我想在我的变量current_cat_id中设置数组值。 我的代码是: -

     this.state = {
    current_cat_id:'',
    }
render() {
return(
          {this.props.data.map((dataImage,Index)=>
            <View key={Index}>      
                {dataImage['main-head'] != undefined && (
                        <View style={{marginRight:20,marginLeft:20,marginBottom:20,width:320,fontSize:16,color:'#000'}}>
                            {dataImage['main-head'].map((subsubchild, Index3)=>
                                <Text>{subsubchild['cat_name']} ({subsubchild['num_rows']})                             
                            </Text>                                                                         
                            )}
                        </View>                     

                )}  
                </View> 
             )}   
)
}

如何将{subsubchild ['cat_name']}设置为current_cat_id。 我试过它:

       {this.props.data.map((dataImage,Index)=>
                <View key={Index}>      
                    {dataImage['main-head'] != undefined && (
                            <View style={{marginRight:20,marginLeft:20,marginBottom:20,width:320,fontSize:16,color:'#000'}}>
                                {dataImage['main-head'].map((subsubchild, Index3)=>
this.setState:({current_cat_id:subsubchild['cat_name']})
                                    <Text>{subsubchild['cat_name']} ({subsubchild['num_rows']})                             
                                </Text>                                                                         
                                )}
                            </View>                     

                    )}  
                    </View> 
                 )} 

但它返回错误。

1 个答案:

答案 0 :(得分:1)

你应该试试这个

componentWillMount() {
    var ids = [];
    this.props.data.map((dataImage) => {
        dataImage['main-head'] != undefined && dataImage['main-head'].map((subchild) => {
            ids.push(subchild['path'])  
            })        
    })
    this.setState({current_cat_id: ids})
}