【问题标题】:onEndReached triggered before data finished loadingonEndReached 在数据加载完成之前触发
【发布时间】:2019-06-17 17:17:01
【问题描述】:

我尝试使用pokeapi.co 创建 PokemonList 我首先获取 /pokemon/ 以获取 /pokemon/{pokemonName} 的列表,然后再次循环以获取我的数据源的详细信息,因为 /pokemon/ 仅提供名称

fetchData(){
  fetch(this.state.urlState)
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          urlState: responseJson.next,
          totalPokemon: responseJson.count
        });
        for (
          let i = 0, p = Promise.resolve();
          i < responseJson.results.length;
          i++
        ) {
          p = p.then(
            _ =>
              new Promise(resolve => {
                fetch(
                  "https://pokeapi.co/api/v2/pokemon/" +
                    responseJson.results[i].name
                )
                  .then(response => response.json())
                  .then(responseJson => {
                    newData = this.state.dataSource;
                    newData.push({
                      id: responseJson.id,
                      name: responseJson.name,
                      sprite: responseJson.sprites.front_default
                    });
                    this.setState({
                      totalFetchedData: this.state.totalFetchedData + 1,
                      dataSource: newData
                    });
                    resolve();
                  });
              })
          );
        }
      })
      .catch(error => {
        console.error(error);
      });
}

这是我的 fetchData 函数

<FlatList
  data={this.state.dataSource}
  onEndReached={() => this.fetchData()}
  onEndReachedThreshold={0.5}
  renderItem={({ item }) => {
    return (
    <View>
      <Text>
        {pokeNumber} - {item.name}
      </Text>
    </View>
    );
  }}
  extraData={this.state}
/>

这是我的 FlatList 组件,我认为 onEndReached 触发是因为列表缺少项目,因此即使第一次加载尚未完成,它也会触发 onEndReached。 onEndReached 是否有任何解决方法,它必须先等待我的 fetchData 完成,然后再获取另一个。

【问题讨论】:

    标签: react-native react-native-android react-native-ios react-native-flatlist


    【解决方案1】:

    有一个关于这个问题的讨论,您可能会找到几个可能的解决方案,您可以从the issue 申请。

    第一你可以做的就是按照这个人在 Github 上的解决方案,它在 FlatList 使用 onMomentumScrollBegin 来防止通过调用而不滚动事件。

    https://github.com/facebook/react-native/issues/14015#issuecomment-310675650

    第二种方法是通过使用计时器(例如来自lodash debounce 的 debounce() )来等待数据获取。但此解决方案可能不起作用,因为它取决于 Internet 和处理速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多