实施拉力以刷新列表



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

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);

设置变量

this.state = { 
    isFetching: false,
}

创建刷新功能

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

以及最后一组,在flatlist上进行刷新。

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

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

this.setState({ isFetching: false })

您也可以在FlatlistScrollView和任何其他列表组件中使用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}
    />
  }
/>
    

如果有人有兴趣与React Hook一起进行此处:

首先创建isRefreshing状态:

const [isRefreshing, setIsRefreshing] = useState(false)

然后创建您的onRefresh函数,该函数调用API刷新数据:

const onRefresh = () => {
    //set isRefreshing to true
    setIsRefreshing(true)
    callApiMethod()
    // and set isRefreshing to false at the end of your callApiMethod()
}

之后,您的FlatList组件看起来像:

return (
    <FlatList
        style={styles.flatList}
        onRefresh={onRefresh}
        refreshing={isRefreshing}
        data={data}
        renderItem={renderItem}
        keyExtractor={item => item.id.toString()}
    />
)

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

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'
        }
      });
const [refreshing, setRefreshing] = useState(false)
    
 <FlatList
     style={{ padding: 15 }}
     refreshControl={
         <RefreshControl 
             refreshing={refreshing} 
             onRefresh={_onRefresh}
             tintColor="#F8852D"/>
     }
     showsVerticalScrollIndicator={false}
     data={listData}
     renderItem={renderItem}
     item={(item, index) => index.toStirng()}
     onEndReachedThreshold={0.8}
     onEndReached={() => onEndReached()}
     ListFooterComponent={() => renderFooter()}
 /> 

_onrefresh函数

const _onRefresh = () => {
    console.log('_onRefresh')
    setRefreshing(true);
    getPosts();
};

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

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

当我将其拉下来时,它不是从服务器中取回数据,该数据由Apollo连接到应用程序,我不知道如何从_GetData()函数中从服务器获取数据。

,而不是使用拉动在平面上的刷新,只需在滚动视图上使用。

设置刷新状态

this.state = { 
     isFetching: false,
  }

在scrollview中设置onfresh

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

在onrefreshfunction

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

您可以检查官方文档:

https://reactnative.dev/docs/refreshcontrol

使用新的React Hooks寻求更新答案的任何人。

您可以从useQuery使用isLoadingrefetch。然后将RefreshControlFlatList一起使用。在RefreshControl上了解更多信息:https://reactnative.dev/docs/refreshcontrol

const RenderImageGrid = (item) => <ImageGrid item={item} />
export const HomeScreen = () => {
    const { data, isLoading, refetch } = useQuery('get_home_screen_data', GET_HOME_SCREEN_DATA)
    return (
        {isLoading ? (
            <Root>
                <Loading size="large" />
            </Root>
        ) : (
            <Root>
                <HomeHeader />
                <FlatList
                    data={data}
                    keyExtractor={item => item._id}
                    renderItem={RenderImageGrid}
                    numColumns={3}
                    refreshControl={
                        <RefreshControl 
                            refreshing={isLoading}
                            onRefresh={refetch} 
                        />
                    }
                />
            </Root>
        )}
    )
}
export default HomeScreen

相关内容

  • 没有找到相关文章

最新更新