简体   繁体   English

试图让嵌套数组与反应原生平面列表一起工作

[英]trying to get a nested array work with react native flat list

so i got this object that i pass as data to my react native flatlist所以我得到了这个 object 作为数据传递给我的 react native flatlist

<FlatList
  extraData = {this.state}
  data = {this.state.data_n1}>
  renderItem = {({item, index}) => {
    this.state.data_n2.forEach(aux => {
      if(item.id == aux.id) {
        return(<View><Text>Display first stuff</Text></View>);
      } else {
        return(<View><Text>Display second stuff</Text></View>);
      }
    }
  }
/>

the whole idea is compare both objects, if the data_n2 contains the same id from the data_n1, the display the data from the data_n2, if not, just display from data_n1, problem is, i'm displaying this whenever i click on a calendar strip, so if i click on day june 1st, that day should display data_n2, if i click on day june 2nd, THAT one should display the data_n1.整个想法是比较两个对象,如果 data_n2 包含来自 data_n1 的相同 id,则显示来自 data_n2 的数据,如果没有,则仅显示来自 data_n1,问题是,每当我点击日历条时,我都会显示这个,所以如果我点击 6 月 1 日,那一天应该显示 data_n2,如果我点击 6 月 2 日,那一天应该显示 data_n1。

does this work with flatlist or virtualizedlist (if i had to swap), or i need to render a flatlist for each data?这是否适用于平面列表或虚拟化列表(如果我必须交换),或者我需要为每个数据呈现一个平面列表?

Edit: tested hao wu answer, but got this编辑:测试了 hao wu 的答案,但得到了这个

在此处输入图像描述

Edit n2: i'll post the code, but keep in mind data_n1 is this.state.listaImputacionDia and this.state.listaImputacionDia is data_n2编辑 n2:我将发布代码,但请记住 data_n1 是 this.state.listaImputacionDia 和 this.state.listaImputacionDia 是 data_n2

this is the calendar strip code这是日历条码

<CalendarStrip
  calendarHeaderStyle={{
    fontSize: rfv(18),
    fontWeight: "normal",
    fontStyle: "normal",
    letterSpacing: 0,
    textAlign: "left",
    color: "#707070",
    paddingBottom: hp('4.5%')
  }}
  selectedDate={this.state.selectedDate}
  onDateSelected={async (date) => {
    await HoursReportHistoryBusiness.GetInstance().getListHoursReportRequest();
    this.setState({ selectedDate: moment(date).format('YYYY-MM-DD') });
    this.setViewHourHistory();
    console.log(this.state.listaImputacionDia);
  }}
  minDate={moment().subtract(3, 'days')}
  maxDate={moment().add(3,'days')}
  startingDate={moment().subtract(3, 'days')}
  useIsoWeekday={false}
  style={{paddingTop: hp('1.5%'), paddingBottom: hp('2.7%'), backgroundColor: '#ffffff'}}
  highlightDateNameStyle={{color: '#1062cc'}}
  highlightDateNumberStyle={{color: '#1062cc'}}
  disabledDateNumberStyle={{color: '#f21927'}}
  disabledDateNameStyle={{color: '#f21927'}}
  customDatesStyles={this.customDatesStyle}
  dateNameStyle={{color: '#c4c4c4'}}
  dateNumberStyle={{color: '#c4c4c4'}}
  disabledDateOpacity={1}
/>

this is the flatlist这是平面清单

<FlatList
  extraData={this.state.listaImputacionDia}
  data={this.state.dataSource}//{DataManager.FavoriteList[moment(this.state.selectedDate).format('YYYY-MM-DD')]}
  renderItem={({ item, index }) => {
    if (this.state.listaImputacionDia.length != 0) {
      const found = this.state.listaImputacionDia.filter(aux => item.id == aux.IdProyecto);
      //this.state.listaImputacionDia.forEach(aux => {
      if (found/*item.id == aux.IdProyecto*/) {
        console.log('la wea' + found);
        return (
          <View style={{ marginTop: hp('2%') }}>
            <TouchableOpacity style={} onPress={() => this.toggleExpanded()}>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <Text numberOfLines={2} ellipsizeMode="tail" style={}>{found.Title}</Text>
                  <Text style={}>{`ID ${found.Id} - ${found.Cliente}`}</Text>
                  {
                    !found.fav ?
                      <Text style={}>No favorito</Text>
                      : null
                  }
                </View>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                    <Text style={}>{`${found.HorasTrabajadas}h`}</Text>
                    <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <Collapsible style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              backgroundColor: "#ffffff",
            }} collapsed={this.state.isCollapsed}>
              <View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={}>Etapa</Text>
                  <Text style={}>Horas</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <ModalDropdown
                    adjustFrame={style => {
                      style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                      return style;
                    }}
                    dropdownTextStyle={styles.dropdownTextStyle}
                    dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                    dropdownStyle={styles.dropdownStageStyle}
                    defaultValue={'Seleccionar'}
                    style={styles.dropStageStyle}
                    textStyle={{
                      padding: 0,
                      margin: 0,
                      fontSize: rfv(16),
                      paddingVertical: hp('1.2%'),
                      fontWeight: 'normal',
                      fontStyle: 'normal',
                      textAlign: 'left',
                      color: found.etapa != '' ? '#1a1a1a' : '#c4c4c4',
                    }}
                    //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                    //options={Object.keys(this.state.items)}
                    onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                    options={DataManager.ListEtapa}
                  />
                  <View style={styles.InputContainerHours}>
                    <Text style={styles.InputTextHours}>{found.HorasTrabajadas}</Text>
                  </View>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                    <Image source={Images.menos_hora} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                    <Image source={Images.mas_hora} />
                  </TouchableOpacity>
                </View>
                <Text style={}>Observaciones</Text>
                <Input
                  autoCapitalize="none"
                  maxLength={100}
                  inputContainerStyle={styles.InputContainerComentarioOnBlur}
                  containerStyle={styles.InputComentario}
                  inputStyle={styles.InputTextHoursRInput}
                  placeholderTextColor={'#c4c4c4'}
                  placeholder="(Opcional)"
                  onChangeText={value => this.setState({})}
                />
                <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                  <Text style={}>Agregar etapa</Text>
                </TouchableOpacity>
              </View>
            </Collapsible>
          </View>
        )
      }
      else {
        console.log('no encontro un favorito');
        return (
          <View style={{ marginTop: hp('2%') }}>
            <TouchableOpacity style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              height: hp('10%'),
              backgroundColor: "#ffffff",
            }} onPress={() => this.toggleExpanded()}>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <Text numberOfLines={2} ellipsizeMode="tail" style={} >{found.title}</Text>
                  <Text style={}>{`ID ${found.id} - ${found.cliente}`}</Text>
                  {
                    !item.fav ?
                      <Text style={}>No favorito</Text>
                      : null
                  }
                </View>
                <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                  <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                    <Text style={}>{`${20}h`}</Text>
                    <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                  </View>
                </View>
              </View>
            </TouchableOpacity>
            <Collapsible style={{
              alignSelf: 'center',
              width: wp('95.7%'),
              backgroundColor: "#ffffff",
            }} collapsed={this.state.isCollapsed}>
              <View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={}>Etapa</Text>
                  <Text style={}>Horas</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <ModalDropdown
                    adjustFrame={style => {
                      style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                      return style;
                    }}
                    dropdownTextStyle={styles.dropdownTextStyle}
                    dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                    dropdownStyle={styles.dropdownStageStyle}
                    defaultValue={'Seleccionar'}
                    style={styles.dropStageStyle}
                    textStyle={}
                    //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                    //options={Object.keys(this.state.items)}
                    onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                    options={DataManager.ListEtapa}
                  />
                  <View style={styles.InputContainerHours}>
                    <Text style={styles.InputTextHours}>{found.horas}</Text>
                  </View>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                    <Image source={Images.menos_hora} />
                  </TouchableOpacity>
                  <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                    <Image source={Images.mas_hora} />
                  </TouchableOpacity>
                </View>
                <Text style={}>Observaciones</Text>
                <Input
                  autoCapitalize="none"
                  maxLength={100}
                  inputContainerStyle={styles.InputContainerComentarioOnBlur}
                  containerStyle={styles.InputComentario}
                  inputStyle={styles.InputTextHoursRInput}
                  placeholderTextColor={'#c4c4c4'}
                  placeholder="(Opcional)"
                  onChangeText={value => this.setState({})}
                />
                <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                  <Text style={}>Agregar etapa</Text>
                </TouchableOpacity>
              </View>
            </Collapsible>
          </View>
        );
      }
      //})
    }
    else {
      console.log('imputacion por dia esta vacio');
      return (
        <View style={{ marginTop: hp('2%') }}>
          <TouchableOpacity style={{
            alignSelf: 'center',
            width: wp('95.7%'),
            height: hp('10%'),
            backgroundColor: "#ffffff",
          }} onPress={() => this.toggleExpanded()}>
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
              <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                <Text numberOfLines={2} ellipsizeMode="tail" style={}>{item.title}</Text>
                <Text style={}>{`ID ${item.id} - ${item.cliente}`}</Text>
                {
                  !item.fav ?
                    <Text style={}>No favorito</Text>
                    : null
                }
              </View>
              <View style={{ flexDirection: 'column', justifyContent: 'center' }}>
                <View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
                  <Text style={}>{`${10}h`}</Text>
                  <Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
                </View>
              </View>
            </View>
          </TouchableOpacity>
          <Collapsible style={{
            alignSelf: 'center',
            width: wp('95.7%'),
            backgroundColor: "#ffffff",
          }} collapsed={this.state.isCollapsed}>
            <View>
              <View style={{ flexDirection: 'row' }}>
                <Text style={}>Etapa</Text>
                <Text style={}>Horas</Text>
              </View>
              <View style={{ flexDirection: 'row' }}>
                <ModalDropdown
                  adjustFrame={style => {
                    style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                    return style;
                  }}
                  dropdownTextStyle={styles.dropdownTextStyle}
                  dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                  dropdownStyle={styles.dropdownStageStyle}
                  defaultValue={'Seleccionar'}
                  style={styles.dropStageStyle}
                  textStyle={}
                  //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                  //options={Object.keys(this.state.items)}
                  onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
                  options={DataManager.ListEtapa}
                />
                <View style={styles.InputContainerHours}>
                  <Text style={styles.InputTextHours}>{item.horas}</Text>
                </View>
                <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
                  <Image source={Images.menos_hora} />
                </TouchableOpacity>
                <TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
                  <Image source={Images.mas_hora} />
                </TouchableOpacity>
              </View>
              <Text style={}>Observaciones</Text>
              <Input
                autoCapitalize="none"
                maxLength={100}
                inputContainerStyle={styles.InputContainerComentarioOnBlur}
                containerStyle={styles.InputComentario}
                inputStyle={styles.InputTextHoursRInput}
                placeholderTextColor={'#c4c4c4'}
                placeholder="(Opcional)"
                onChangeText={value => this.setState({})}
              />
              <TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
                <Text style={}>Agregar etapa</Text>
              </TouchableOpacity>
            </View>
          </Collapsible>
        </View>
      );
    }
  }}
/>

forEach only returns undefined , no matter what you return in the function. forEach只返回undefined ,无论您在 function 中返回什么。

You could find the element first, and then render it conditionally:你可以先找到元素,然后有条件地渲染它:

<FlatList
    extraData={this.state.data_n2}
    data={this.state.data_n1}>
    renderItem = {({ item, index }) => {
        const found = this.state.data_n2.find(aux => item.id == aux.id);
        if (found) {
            return (<View><Text>Display first stuff: {found.id}</Text></View>);
        } else {
            return (<View><Text>Display second stuff: {item.id}</Text></View>);
        }
    }}
/>

If there are possibly multiple matches:如果可能有多个匹配项:

<FlatList
    extraData={this.state}
    data={this.state.data_n1}>
    renderItem = {({ item, index }) => {
        const found = this.state.data_n2.filter(aux => item.id == aux.id);
        if (found.length > 0) {
            return (
                <View>{
                    found.map(e => (<View><Text>Display first stuff: {e.id}</Text></View>))
                }</View>
            );
        } else {
            return (<View><Text>Display second stuff</Text></View>);
        }
    }}
/>

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

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