Отображение массива в JavaScript для динамического рендеринга данных - PullRequest
0 голосов
/ 19 октября 2019

У меня есть массив предметов, которые я получил от объекта. В массиве 5 предметов. Это выглядит так:

enter image description here

Я сохранил массив в моем состоянии как:

this.state={

    serviceDetails: planDetails[0].nbs_plans.map(service => service.extension_attributes.productServicetList.map(name=>name.name)),
}

Теперь я пытаюсьдля рендеринга массива в моем компоненте, используя функцию карты, например:

 {
             this.state.serviceDetails.map((serviceName) => {
               return (
<SelectableChips initialChips={serviceName} />
               );
             })
           }

Но проблема в том, что все массивы собираются вместе в одном месте, как показано ниже:

enter image description here

То, как это должно быть так: первый «Видеть больше» должен быть в первом разделе, второй - во втором и т. Д.

Мой полный код для этого компонента выглядит следующим образом:

//This is an example code for FlatList//
import React from 'react';
import {
 StyleSheet, FlatList, Text, View, Alert , Image, TouchableOpacity 
} from 'react-native';
import SelectableChips from '../../../components/Chip/SelectableChips';
import CheckBox from '../../../components/CheckBox';
import propTypes from 'prop-types';
import Service from './Service';
import { planDetails } from '../../../api/mockedData/PlanServiceDetails';
class Selected_Items_Array {

  constructor() {
    selectedItemsArray = [];
    this.state = {
      planName: planDetails[0].nbs_plans.map(data => data.name),
      serviceDetails: planDetails[0].nbs_services.map(data => data.service_line),
    };
    var result = planDetails.filter(d => {
      return d.nbs_plans[0].name = "TruComplete℠ Lawn Care Plan";
    });
  //  alert(Object.keys(planDetails).length);
  //  alert(Object.keys(planDetails[0].nbs_plans).length);
  //  alert(JSON.stringify(planDetails[0].nbs_plans[0].productId));

  // alert(JSON.stringify(planDetails[0].nbs_plans[0].name));
  // alert(JSON.stringify(planDetails[0].nbs_plans.map(data => data.name)));
  }

  pushItem(option) {
    selectedItemsArray.push(option);
  }

  getArray() {
    return selectedItemsArray;
  }
}
export default class Services extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      // FlatListItems: [
      //   { id: '1', value: 'TruGreen Mosquito Defense' ,applicationType:'annual' },
      //   { id: '2', value: 'Sprinkler Maintenance Program' ,applicationType:'first' },
      //   { id: '3', value: 'Soil Treatment to balance the PH of the lawn-' ,applicationType:'priceper'},
      //   { id: '4', value: 'Tree & Shrub Care' ,applicationType:'customquote'},


      // ],

      planName: planDetails[0].nbs_plans.map(data=>data.name),
      serviceDetails: planDetails[0].nbs_plans.map(service => service.extension_attributes.productServicetList.map(name=>name.name)),

    };
    selectedArrayOBJ = new Selected_Items_Array();
    alert(JSON.stringify(planDetails[0].nbs_plans.map(data => data.name)));
    alert(JSON.stringify(planDetails[0].nbs_plans[0].extension_attributes.productServicetList.map(data=> data.name)));
    alert(JSON.stringify(planDetails[0].nbs_plans.map(service => service.extension_attributes.productServicetList.map(name=>name.name))));
    alert(this.state.planName);
    alert(this.state.serviceDetails);
  }

  FlatListItemSeparator = () => {
    return (
      //Item Separator
      <View
        style={{ height: 7, width: '100%', backgroundColor: 'transparent' }}
      />
    );
  };

  GetItem(item) {
    //Function for click on an item
    Alert.alert(item);
  }




  render() {

    return (

      <View style={styles.MainContainer}>

        <FlatList
          data={this.state.planName}
          //data defined in constructor
          ItemSeparatorComponent={this.FlatListItemSeparator}
          //Item Separator View
          renderItem={({ item }) => (
            // Single Comes here which will be repeatative for the FlatListItems
         <View style={styles.cellContainerStyle} >
           <View backgroundColor = {"transparent"}   flexDirection = {'row'} justifyContent= {'flex-start'} margin={0}>
               <View  backgroundColor={'#73c573'}     justifyContent= {'center'} alignItems={'center'} width={35} height={35} marginTop={0} paddingTop={0}>
                 <View backgroundColor={'#73c573'} width={25} height={25}>
                   <CheckBox size={25}
                    keyValue={1}
                    selectedArrayObject={selectedArrayOBJ}
                    checked={false}
                    label = ''
                    color="transparent"
                    labelColor="#00703c"
                    checkBoxClick={this.checkBoxOnClicked}/>
                 </View>
               </View>
               <View flex={1.75} backgroundColor={'transparent'} marginLeft={5}>
                      <Text style={{ color: '#00703c', fontSize: 21, fontFamily: 'SourceSansPro-Bold' }}> {item}</Text>
                      </View>
               <View flex={0.15} marginTop={10}>
                    <TouchableOpacity style = {{ backgroundColor: 'transparent' }} onPress = {this.props.seeMore}  >
                       <Image source={require('../../../assets/img/iOS/chevron_right.png')} style={styles.rightArrowImageStyle}/>
                    </TouchableOpacity>
               </View>
        </View>
           <View  style={styles.cellSubViewTwo}>
         <Text  style = {styles.textHeaderStyle}>This plan includes:</Text>
         <View backgroundColor = {"transparent"}     flexDirection='column' marginTop={5}>
           {
             this.state.serviceDetails.map((serviceName) => {
               return (
<SelectableChips selectedChipStyle={selectableStyles} initialChips={serviceName} onChangeChips={(chips) => console.log(chips)} alertRequired={false} backgroundColor={"transparent"}
           subView={
            <TouchableOpacity style = {{ backgroundColor: 'transparent' }} onPress = {this.props.seeMore}  >
            <View backgroundColor={'transparent'} flexDirection = {'row'} alignItems= {'center'} marginLeft={5}>
            <Text style={styles.seeMoreStyle}>See more</Text>
               <Image source={require('../../../assets/img/iOS/chevron_right.png')} style={styles.rightArrowSeeMoreImageStyle}/>
            </View>
             </TouchableOpacity>
           }/>
               );
             })
           }

         </View>
        </View>
           <Service serviceType={item.applicationType} isButton={false}/>
        </View>
          )}
        />
      </View>
    );
  }

  checkBoxOnClicked() {

    if (selectedArrayOBJ.getArray().length == 0) {
      //Alert.alert('CheckBox UnChecked');
    } else {
      // Alert.alert('CheckBox Checked');
    }
  }

}
Services.propTypes = { seeMore: propTypes.string.isRequired };

const styles = StyleSheet.create({
  MainContainer: {
    justifyContent: 'center',
    margin: 7,
    backgroundColor: 'transparent',
  },

  cellContainerStyle: {
    padding: 0,
    fontSize: 18,
    flexDirection: 'column',
    backgroundColor: '#ffffff',
    borderColor: 'lightgray',
    borderWidth: 0.5,

  },
  cellSubViewOne: {
    flexDirection: 'row',

  },
  cellSubViewTwo: {
    flexDirection: 'column',
    marginLeft: 15,
    backgroundColor: "#ffffff",
    marginTop: 15,
  },
  cellSubViewThree: {
    flexDirection: 'column',
    marginLeft: 0,
    backgroundColor: "#eff5ef",
    marginTop: 15,

  },
  textHeaderStyle: {
    color: '#73c573',
    fontSize: 10.5,
    fontFamily: "SourceSansPro-SemiBold",
  },
  rightArrowImageStyle: {
    height: 12,
    width: 12,
    resizeMode: 'center',
    alignItems: 'center',
    tintColor: '#a6a6a6',
  },
  rightArrowSeeMoreImageStyle: {
    height: 8,
    width: 8,
    resizeMode: 'center',
    alignItems: 'center',
    tintColor: '#ff9933',
  },
  seeMoreStyle: {
    fontSize: 11,
    color: '#ff9933',
    fontFamily: "SourceSansPro-SemiBold",

  },

});

const selectableStyles = StyleSheet.create({
  chip: {
    backgroundColor: '#73c573',
    borderColor: '#73c573',
    borderWidth: 1,
    margin: 3,
    padding: 0,
    borderRadius: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  valueStyle: {
    color: '#ffffff',
    fontSize: 12,
    fontFamily: "SourceSansPro-Regular",
  },
  chipSelected: {
    backgroundColor: '#73c573',
    borderColor: '#73c573',
    borderWidth: 1,
    margin: 3,
    padding: 0,
    borderRadius: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  valueStyleSelected: {
    color: '#ffffff',
    fontSize: 12,
    fontFamily: "SourceSansPro-Regular",

  },

});

Может кто-нибудь, пожалуйста, подскажите мне, как действовать.

1 Ответ

0 голосов
/ 19 октября 2019

Поскольку каждый план имеет productServicetList, создайте объект serviceDetails, ключом которого является planName, а значением будет productServicetList.

this.state={
    serviceDetails: planDetails[0].nbs_plans.reduce(
      (acc, service) => ({
        ...acc,
        [service.name]: service.extension_attributes.productServicetList.map(
          name => name.name
        )
      }),
      {}
    );
}

Затем выполните визуализацию serviceDetail следующим образом

  {
    this.state.serviceDetails[item].map(serviceName => {
      return <SelectableChips initialChips={serviceName} />;
    });
  }
...