0

如何限制滚动视图内的视图数量。

我的组件渲染时间太长,因为 map 函数渲染了太多视图。我只需要显示 10 个视图,向上滚动时会呈现更多 10 个视图。

我正在使用本机反应、钩子和打字稿。

4

2 回答 2

2

首先,如果您有大量列表数据,请不要使用滚动视图。因为最初,它会将所有数据加载到滚动视图组件,并且也会降低性能。

在 react-native 中使用flatlist而不是 scrollview 并且您可以限制最初使用initialNumToRender渲染的项目数量。当您到达滚动位置的末尾时,您可以调用onEndReached方法来加载更多数据。

一个样本会像这样

import React, { Component } from "react";
import { View, Text, FlatList, ActivityIndicator } from "react-native";
import { List, ListItem, SearchBar } from "react-native-elements";

class FlatListDemo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data: [],
      page: 1,
      seed: 1,
      error: null,
      refreshing: false
    };
  }

  componentDidMount() {
    this.makeRemoteRequest();
  }

  makeRemoteRequest = () => {
    const { page, seed } = this.state;
    const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: page === 1 ? res.results : [...this.state.data, ...res.results],
          error: res.error || null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({ error, loading: false });
      });
  };

  handleRefresh = () => {
    this.setState(
      {
        page: 1,
        seed: this.state.seed + 1,
        refreshing: true
      },
      () => {
        this.makeRemoteRequest();
      }
    );
  };

  handleLoadMore = () => {
    this.setState(
      {
        page: this.state.page + 1
      },
      () => {
        this.makeRemoteRequest();
      }
    );
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%"
        }}
      />
    );
  };

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />;
  };

  renderFooter = () => {
    if (!this.state.loading) return null;

    return (
      <View
        style={{
          paddingVertical: 20,
          borderTopWidth: 1,
          borderColor: "#CED0CE"
        }}
      >
        <ActivityIndicator animating size="large" />
      </View>
    );
  };

  render() {
    return (
      <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem
              roundAvatar
              title={`${item.name.first} ${item.name.last}`}
              subtitle={item.email}
              avatar={{ uri: item.picture.thumbnail }}
              containerStyle={{ borderBottomWidth: 0 }}
            />
          )}
          keyExtractor={item => item.email}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          ListFooterComponent={this.renderFooter}
          onRefresh={this.handleRefresh}
          refreshing={this.state.refreshing}
          onEndReached={this.handleLoadMore}
          onEndReachedThreshold={50}
        />
      </List>
    );
  }
}

export default FlatListDemo;

检查此以获取更多信息。

于 2019-12-11T18:32:04.117 回答
0

我改为平面列表!但是 initialNumToRender 没有按预期工作。

flatlist 正在呈现所有 150 笔交易,而不仅仅是 15 笔,我不知道该怎么做。

我正在从另一个数组运行 .map() 以及所有其他事务,以仅使用我想要使用的那些事务创建 newMonths data={newMonths}

  let newMonths = [];
  const createArrayMonth = histInfos.map(function (info) {
    if (info.created_at.slice(5, 7) === month) {
      newMonths = [info].concat(newMonths);
    }
  });

他们,我创建了我的组件:

  function Item({ value }: { value: any }) {
    let createdDay = value.item.created_at.slice(8, 10);
    let createdMonth = value.item.created_at.slice(5, 7);
    let createdYear = value.item.created_at.slice(2, 4);
    function dateSelected() {
      if (
        month === createdMonth &&
        year === createdYear &&
        (day === '00' || day == createdDay)
      ) {
        console.log('foi dateSelected');
        const [on, setOn] = useState(false);
        const Details = (on: any) => {
          if (on === true) {
            return (
              <View style={styles.infos}>
                <Text style={styles.TextInfos}>
                  {' '}
                  CPF/CNPJ: {value.item.cpf_cnpj}{' '}
                </Text>
                <Text style={styles.TextInfos}>
                  {' '}
                  Criado em: {value.item.created_at}{' '}
                </Text>
                <Text style={styles.TextInfos}>
                  {' '}
                  Endereço da carteira: {value.item.address}{' '}
                </Text>
                <Text style={styles.TextInfos}> Valor: {value.item.amount}BTC </Text>
              </View>
            );
          } else {
            return <View />;
          }
        };
        return (
          <View>
            <TouchableOpacity
              style={styles.card}
              onPress={() => setOn(oldState => !oldState)}>
              <View style={styles.dateStyleView}>
                <Text style={styles.dateStyle}>{createdDay}</Text>
              </View>
              <View style={styles.left}>
                <Text style={styles.title}>Venda rápida</Text>
                <Text style={styles.semiTitle}>
                  {
                    {
                      0: 'Pendente',
                      1: 'Aguardando conclusão',
                      2: 'Cancelado',
                      100: 'Completo',
                    }[value.item.status]
                  }
                </Text>
              </View>
              <View style={styles.right2}>
                <Text style={styles.price}>R$ {value.item.requested_value}</Text>
              </View>
            </TouchableOpacity>
            <View>{Details(on)}</View>
          </View>
        );
      }
    }
    return dateSelected();}

我在这里称呼它

return (
<ScrollView>
 ...
  <View style={styles.center}>
    ...
    <View style={styles.middle2}>
       ...
        <FlatList
          extraData={[refresh, newMonths]}
          data={newMonths}
          renderItem={(item: any) => <Item value={item} />}
          keyExtractor={(item, index) => index.toString()}
          initialNumToRender={15}
        />


    </View>
  </View>
</ScrollView>);}

右侧的滚动条,开始增加,直到从数据中呈现所有事务: 应用滚动条

于 2019-12-12T21:03:44.373 回答