亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ListFooterComponent 不能正常工作?

ListFooterComponent 不能正常工作?

繁花不似錦 2022-06-16 17:28:38
我對 Flatlist 有一個奇怪的問題,當我向下滾動時,我從 API 獲取了數據,我增加了頁面 +1,在頁腳中,我渲染了一個微調器,但是當最后一頁 == 當前頁面時,這意味著除了微調器沒有數據來卡在底部,盡管我將其更新為假!那么這里有什么問題!順便說一句,當我在 FlatList 中以這種方式調用 renderFooterListFooterComponent={()=> this._renderFooter()} // it disappeare the bottom spiner if last page == current page but I have an unexpected re-rendering and app laggay and in some time spinner disappeared even I scrolling to bottom!!代碼class LastSongs extends React.PureComponent {  constructor() {    super();    this.state = {      songs: [],      loading: false,      page: 1,      last_page: 1,    };    this.isCancelled = false;  }  manipulateArray = async (array) => {    let songs = [];    array.map((track) =>      songs.push({        id: track.id,        name: track.name,        url: URL + track.sounds,        img: URL + track.avatar,      }),    );    return songs;  };  getData = async () => {    try {      this.setState({loading: true});      let response = await API.get(`/tracks?page=${this.state.page}`);      let lastPage = response.data.data.items.last_page;      let {        data: {          data: {            items: {data},          },        },      } = response;      let All_Songs = await this.manipulateArray(data);      this.setState({        songs: this.state.songs.concat(All_Songs),        last_page: lastPage,      });    } catch (err) {      console.log('err', err);    }  };  _renderItems = ({item, index}) => (    <TouchableNativeFeed      key={item.id}      onPress={() => {        this.props.saveSongs(this.state.songs, index);        this.props.isPlaying(true);        this.props.isPauseTrigger(!this.props.isPauseTrigger);      }}  );
查看完整描述

1 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

當您滾動到底部時,您正在調用一個超時的異步函數。該超時將覆蓋您的以下代碼并將 loading 再次設置為 true。所以在這種情況下加載永遠不會是錯誤的。


 } else if (this.state.page === this.state.last_page) {

      this.setState({loading: false}, () =>

        console.log('if--loading', this.state.loading), // log false!! that's mean a spinner should disapeare

      );

 }

你在這里需要兩件事。


1) 嘗試在你的 catch 塊中將 loading 設置為 false。


} catch (err) {

   console.log('err', err);

   this.setState({loading: false});

}

2) 在您的狀態中添加另一個isAllDataFetched初始值為 false 的值。當您從 API 接收到空數據時,將 loading 設置為 false。不確定您的數據如何,但可以執行以下操作;


getData = async () => {

    try {

      this.setState({loading: true});

      let response = await API.get(`/tracks?page=${this.state.page}`);

      let lastPage = response.data.data.items.last_page;

      let {

        data: {

          data: {

            items: {data},

          },

        },

      } = response;


      // if it's an array

      if(data.length === 0) {

         this.setState({loading: false, isAllDataFetched: true});

      }

      //...

    } catch (err) {

      console.log('err', err);

    }

  };

最后,在您的 handleLoadMore 方法中添加以下行。


handleLoadMore = () => {

 if(this.state.isAllDataFetched) return;

我為你創建了一個演示。您可以按照此邏輯使其工作。它與你所擁有的有點不同,但我認為它會有所幫助。


這是代碼。


import React from 'react';

import {

  View, Text, FlatList, ActivityIndicator, SafeAreaView

} from 'react-native';



class App extends React.PureComponent {

  state = {

    songs: [

      {

        userId: 1,

        id: 1,

        title: 'delectus aut autem 1',

        completed: false,

      },

      {

        userId: 1,

        id: 2,

        title: 'delectus aut autem 2',

        completed: false,

      },

    ],

    loading: false,

    page: 3,

    totalPage: 10,

  };


  componentDidMount() {

    this.getData();

  }


  getData = async () => {

    const { songs } = this.state;

    try {

      this.setState({ loading: true });

      const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${this.state.page}`, {

        headers: {

          'Content-Type': 'application/json',

        },

      });

      const json = await response.json();


      this.setState({

        songs: [...songs, json],

      });

      this.setState({ loading: false });

    } catch (err) {

      console.log('err', err);

      this.setState({ loading: false });

    }

  };


  renderItems = ({ item }) => (

    <Text style={{ backgroundColor: 'blue', height: 200, marginBottom: 5 }}>{`${item.title}-${item.id}`}</Text>

  );


  onEndReached = () => {

    const { page, loading, totalPage } = this.state;


    if (loading) return;


    if (page <= totalPage) {

      this.setState({ loading: true, page: page + 1 }, () =>

        setTimeout(() => {

          this.getData();

        }, 2000));

    } else {

      this.setState({ loading: false });

    }

  }


  renderFooter = () => {

    const { loading } = this.state;


    if (loading) {

      return (

        <View>

          <ActivityIndicator color="#000" size="large" />

        </View>

      );

    }

    return null;

  }


  renderListEmptyComponent = () => <View />;


  render() {

    const { songs } = this.state;

    return (

      <SafeAreaView style={{ flex: 1, backgroundColor: 'red' }}>

        <FlatList

          data={songs}

          keyExtractor={song => song.id}

          initialNumToRender={10}

          contentContainerStyle={{ flexFrow: 1, backgroundColor: 'white' }}

          style={{ flex: 1 }}

          ListEmptyComponent={this.renderListEmptyComponent}

          renderItem={this.renderItems}

          onEndReached={this.onEndReached}

          onEndReachedThreshold={0.7}

          ListFooterComponent={this.renderFooter}

        />

      </SafeAreaView>

    );

  }

}

export default App;

這里有一個工作演示(使用 iOS 設備)


查看完整回答
反對 回復 2022-06-16
  • 1 回答
  • 0 關注
  • 322 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號