首页 > 解决方案 > 如何在每次映射函数迭代后渲染不同的组件

问题描述

我正在从http://retailsolution.pk/api/allhome获取数据我想显示产品的标题,然后显示它下面的所有子产品,我得到这个输出:在此处输入图像描述这是我的代码:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Deals: []
    };
  }
  componentWillMount() {
    axios
      .get("https://retailsolution.pk/api/allhome")
      .then(response => this.setState({ Deals: response.data.Deals }));
  }

  _renderItem(item) {
    return (
      <View style={{ width: 100, height: 130 }}>
        <Image
          style={{ width: 100, height: 100 }}
          source={{ uri: item.image }}
        />
        <Text numberOfLines={1} style={{ flex: 1 }}>
          {" "}
          {item.name}
        </Text>
      </View>
    );
  }

  renderTitle() {
    return this.state.Deals.map(deal => (
      <Text key={deal.parent.id} style={styles.text}>
        {deal.parent.name}
      </Text>
    ));
  }
  renderImage() {
    return this.state.Deals.map(deal => (
      <FlatList
        key={deal.child.product_id}
        style={{ marginTop: 5 }}
        horizontal
        ItemSeparatorComponent={() => <View style={{ width: 5 }} />}
        renderItem={({ item }) => this._renderItem(item)}
        data={[deal.child]}
      />
    ));
  }
  render() {
    console.log(this.state.Deals);
    return (
      <View style={{ flex: 1, marginLeft: 8, marginRight: 8, marginTop: 10 }}>
        {this.renderTitle()}
        {this.renderImage()}
      </View>
    );
  }
}

在我的情况下{this.renderTitle()},首先执行并将每个值从 api 映射到应用程序,然后{this.renderImage()}将所有平面列表映射到应用程序。

有什么方法可以在每次迭代 rhis.renderTitle() 之后运行 this.renderImage() 吗?

标签: javascriptreactjsreact-native

解决方案


您将不得不使用嵌套循环来完成它。尝试这样的事情 -

{this.state.Deals.map(deal => {
  return (
    <div>
      <Text key={deal.parent.id} style={styles.text}>
        {deal.parent.name}
      </Text>
      {deal.child.map(item => {
        return (
          <FlatList
            key={item.product_id}
            style={{ marginTop: 5 }}
            horizontal
            ItemSeparatorComponent={() => <View style={{ width: 5 }} />}
            renderItem={({ item }) => this._renderItem(item)}
            data={[item]}
          />
        );
      })}}
    </div>
  );
})}

推荐阅读