Javascript 实现 pull 刷新 FlatList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47570998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:52:33  来源:igfitidea点击:

Implement pull to refresh FlatList

javascriptreact-nativeexpo

提问by petros

please help me out to implement pull to refresh on my app, I'm kinda new to react native, thanks. I don't know how to handle onRefresh and refreshing.

请帮助我在我的应用程序上实现拉动刷新,我对原生反应有点陌生,谢谢。我不知道如何处理 onRefresh 和刷新。

class HomeScreen extends Component {
  state = { refreshing: false }

  _renderItem = ({ item }) => <ImageGrid item={item} />

  _handleRefresh = () => {

  };

  render() {
    const { data } = this.props;
    if (data.loading) {
      return (
        <Root>
          <Loading size="large" />
        </Root>
      )
    }
 return (
   <Root>
     <HomeHeader />
     <FlatList
       contentContainerStyle={{ alignSelf: 'stretch' }}
       data={data.getPosts}
       keyExtractor={item => item._id}
       renderItem={this._renderItem}
       numColumns={3}
       refreshing={this.state.refreshing}
       onRefresh={this._handleRefresh}
     />
   </Root>
  );
 }
}

export default graphql(GET_POSTS_QUERY)(HomeScreen);

回答by krish

Set variable

设置变量

  this.state = { 
     isFetching: false,
  }

Create Refresh function

创建刷新功能

  onRefresh() {
       this.setState({isFetching: true,},() => {this.getApiData();});
  }

And in last set onRefresh and refreshing in FlatList.

并在最后一组 onRefresh 和 FlatList 中刷新。

  <FlatList
      data={ this.state.FlatListItems }
      onRefresh={() => this.onRefresh()}
      refreshing={this.state.isFetching}

After fetching Data in function getApiData Make sure to set false isFetching.

在函数 getApiData 中获取数据后,请确保设置 false isFetching。

this.setState({ isFetching: false })

回答by Jigar

you can also use refreshControl in Flatlist ScrollView and any other list component

您还可以在 Flatlist ScrollView 和任何其他列表组件中使用 refreshControl

<FlatList
       contentContainerStyle={{ alignSelf: 'stretch' }}
       data={data.getPosts}
       keyExtractor={item => item._id}
       renderItem={this._renderItem}
       numColumns={3}
       refreshControl={
          <RefreshControl
           refreshing={this.state.refreshing}
           onRefresh={this._handleRefresh}
          />
        }
     />

回答by Rishav Kumar

// Sample code representing pull to refresh in flatlist. Modify accordingly.

// 表示在 flatlist 中拉动刷新的示例代码。相应地修改。

import React, { Component } from 'react'
    import { Text, View,StyleSheet,FlatList,Dimensions,Image,TouchableHighlight } from 'react-native'

    export default class Home extends Component {

        constructor(props) 
        {
            super(props);
        this.state = {
            data : [],
            gender : "",
            isFetching: false,
        }
        }

    componentWillMount()
    {

        this.searchRandomUser()
    }

    onRefresh() {
        this.setState({ isFetching: true }, function() { this.searchRandomUser() });
     }

    searchRandomUser = async () =>
    {
       const RandomAPI = await fetch('https://randomuser.me/api/?results=20')
       const APIValue = await RandomAPI.json();
        const APIResults = APIValue.results
          console.log(APIResults[0].email);
          this.setState({
              data:APIResults,
              isFetching: false
          })

    }

      render() {
        return (
          <View style = {styles.container}>
     <TouchableHighlight
     onPressOut = {this.searchRandomUser}
         style = {{width:deviceWidth - 32, height:45,backgroundColor: 'green',justifyContent:"center",alignContent:"center"}}>
              <Text style = {{fontSize:22,color: 'white',fontWeight: 'bold',textAlign:"center"}}>Reload Data</Text>
         </TouchableHighlight>
     <FlatList
            data={this.state.data}
            onRefresh={() => this.onRefresh()}
          refreshing={this.state.isFetching}
            keyExtractor = { (item, index) => index.toString() }
            renderItem={({item}) =>
            <View style = {styles.ContainerView}>
            <View>
    <Image
    source={{uri : item.picture.large}}
    style = {{height:100,width:100,borderRadius: 50,marginLeft: 4}}
    resizeMode='contain'
    />
    </View>

    <View style = {{flexDirection: 'column',marginLeft:16,marginRight: 16,flexWrap:'wrap',alignSelf:"center",width: deviceWidth-160}}>
    <Text>Email Id : {item.email}</Text>

    <Text>Full Name : {this.state.gender} {item.name.first} {item.name.last}</Text>
    <Text>Date of birth : {item.dob.age}</Text>
    <Text>Phone number : {item.phone}</Text>

    </View>

    </View>
            }
            />
          </View>
        )
      }
    }
    const deviceWidth = Dimensions.get('window').width
    const deviceHeight = Dimensions.get('window').height
    const styles = StyleSheet.create({
        container: {
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
          marginTop:22
        },
        ContainerView:
        {
            // backgroundColor:'grey',
            marginBottom:20,
            paddingVertical:10,
            backgroundColor: '#F5F5F5',

            borderBottomWidth:0.5,
            borderBottomColor:'grey',
            width: deviceWidth-40,
            marginLeft:20,
            marginRight:20,
            marginTop:20,
            flexDirection:'row'
        }
      });

回答by Danish Hassan

Instead of using pull to refresh on flat-list simply use on Scroll View.

无需使用 pull 在平面列表上刷新,只需在 Scroll View 上使用即可。

Set Refresh State

设置刷新状态

this.state = { 
     isFetching: false,
  }

Set onFresh in ScrollView

在 ScrollView 中设置 onFresh

<ScrollView
  refreshControl={
    <RefreshControl
      refreshing={this.state.refresh}
      onRefresh={() => this.onRefresh()}
      tintColor="red"
    />
  }>
  <FlatList data={data} renderItem={this._renderItem} numColumns={3} />
</ScrollView>;

In OnRefreshFunction

在 OnRefresh 函数中

  onRefresh() {
    this.setState({refresh: true});
    setTimeout(() => {
      this.setState({refresh: false});
    }, 2000);
  }

回答by Teivaz

"Pull to refresh" concept implies that the list can be manually refreshed thus can be changed outside the current view (e.g. fetched from server). So the callback onRefreshhas to trigger the data reloading process (e.g. send a request to the server) and set the refreshingvariable to truthy value. This will notify the user that the process was started by showing loading indicator. Once you got the data ready you need to set refreshingto falsy so the view will hide loading indicator.

“拉动刷新”概念意味着列表可以手动刷新,因此可以在当前视图之外进行更改(例如从服务器获取)。因此回调onRefresh必须触发数据重新加载过程(例如向服务器发送请求)并将refreshing变量设置为真值。这将通过显示加载指示器通知用户进程已启动。准备好数据后,您需要将其设置refreshing为 falsy,以便视图将隐藏加载指示器。

回答by petros

this is the best that I can do. my Code Image

这是我能做的最好的。我的代码图片

when I pull it down it dosen't refetch data from server I'm running graphql server which connected by Apollo to the app, and I don't know how to get data from server in _getData() function.

当我把它拉下来时,它不会从服务器重新获取数据我正在运行由 Apollo 连接到应用程序的 graphql 服务器,我不知道如何在 _getData() 函数中从服务器获取数据。