简体   繁体   English

对本地搜索结果反应太大,需要分页

[英]react native search result too large and need pagination

i am new to this react native and i am require to develop a simple app to search something from given api. 我是这个反应本机的新手,我需要开发一个简单的应用程序来从给定的api中搜索内容。 Given api does not have pages but count of results and sometimes the results that comes out is large 给定的api没有页面,但是结果计数很多,有时结果出来的结果很大

this case, my search result is loading while displaying some of the result from the api. 在这种情况下,我的搜索结果正在加载,同时显示api的一些结果。 I found out this to be very bad design for myself and i wanted to do something like load only 10 result first and when scroll until end will load another 10 results and keep on going with 10 results. 我发现这对我自己来说是一个非常糟糕的设计,我想做些类似的事情,例如先加载仅10个结果,然后滚动到结束将再加载10个结果并继续处理10个结果。 I think this is call infinite scrolling? 我认为这就是所谓的无限滚动?

during my search in google, i see alot of example but i am not sure how to implement this on my side instead. 在Google搜索期间,我看到了很多示例,但是我不确定如何在我这一边实现它。 This is my search code. 这是我的搜索代码。

import React, { Component } from 'react';
import { StyleSheet, Alert, Dimensions, Platform, View,TouchableOpacity,TouchableHighlight,FlatList  } from 'react-native'
import { Button,Header, Icon, Input, Item, Left, Right, Text,Thumbnail } from 'native-base'
import { ListItem, Avatar } from 'react-native-elements'


const { width, height } = Dimensions.get('window')
class Search extends Component {
  constructor(){
    super();
    this.state = {
      searchResult: [],
    };
  }

   static navigationOptions = {
   title: "Search Results",
             headerStyle: {
              backgroundColor: '#4050B5',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
              fontWeight: 'bold'
    }
  };

  getSearchResult(searchURL){
    console.log("Search URL is => "+searchURL);
    return fetch(searchURL)
    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({searchResult:responseJson.result});
    })
    .catch((error) => {
      console.error(error);
    });
  }

  configureSearchURL(props){
    const { navigation } = props;
    let selectedTitles = navigation.getParam('selectedTitles');
    let searchKeyword = navigation.getParam('searchKeyword');
    console.log("selectTitles => "+selectedTitles);
    console.log("searchKeyword => "+searchKeyword);
    let searchURL = 'https://imas-go.com/test_item_search.php?';
    let titleParameter = "";

    if(selectedTitles != null || selectedTitles != ""){
       for (let i=0;i<selectedTitles.length;i++){
        if(i==0){
          titleParameter+="vers[]="+selectedTitles[i];
        } else {
          titleParameter+="&vers[]="+selectedTitles[i];
        }
      }
      searchURL+=titleParameter;
    }

    if(searchKeyword.trim().length > 0){
      searchURL+="&name="+searchKeyword;
    }
    console.log("final search url => "+searchURL);
    this.getSearchResult(searchURL);
  }

  componentDidMount(){
   this.configureSearchURL(this.props);
  }

  keyExtractor = (item, index) => item.sno+item.name;

renderItem = ({ item }) => (
 <ListItem
      title= {item.name}
      subtitle={
        <View style={styles.subtitleView}>
          <Text style={styles.ratingText}>Ver: {item.ver}</Text>
          <Text style={styles.ratingText}>Price: {item.price}</Text>
          <Text style={styles.ratingText}>Stock: {item.stock}</Text>
        </View>
      }
     avatar={<Avatar
                large
                medium
                source={{uri: `https://imas-go.com/card_image/ws/front/${item.ver}/${item.cid}.jpg`}}
                onPress={() => console.log("Works!")}
              />}
    />
)   
  render() {

      return(
        <FlatList
      keyExtractor={this.keyExtractor}
      data={this.state.searchResult}
      renderItem={this.renderItem}
    />

        );
  }
}

styles = StyleSheet.create({
  subtitleView: {
    flexDirection: 'row',
    paddingLeft: 10,
    paddingTop: 5
  },
  ratingText: {
    paddingLeft: 10,
    color: 'grey'
  }
})

export default Search;

i have a page that searches with keywords and category and redirect to this search.js page and form the parameter for the api search url. 我有一个页面,可以搜索关键字和类别,然后重定向到此search.js页面,并形成api搜索网址的参数。 Hope someone can help me in implement this 希望有人可以帮助我实现这一目标

Try using flatlist, That will take a few set of data and lazy loads the rest. 尝试使用平面列表,这将需要一些数据,而延迟加载其余数据。

https://facebook.github.io/react-native/docs/flatlist https://facebook.github.io/react-native/docs/flatlist

You could create a new state called "currentView" which refers to this.currentView() like this: 您可以创建一个称为“ currentView”的新状态,该状态引用this.currentView()如下所示:

this.state = {
  currentView: this.currentView(),
  currentPagination: []
}

And then you simply define a for loop like this: 然后,您只需定义一个for循环,如下所示:

currentView() {
 let pagination = 10; // Set how many you want to show each time
 let list = []; // The list you will render
 let currentPagination = this.state.currentPagination.length

 for (let i = 0; i < pagination; i++) {
     let arr = this.state.searchresults.slice(currentPagination)
     list.push(arr[i]);
 };
 this.setState({currentPagination: list})

 return list;
}

To make it load when you scroll you'll need to set something up in componentDidUpdate() , something like this: 要在滚动时加载它,您需要在componentDidUpdate()进行设置,如下所示:

componentDidUpdate() {
  let windowHeight = window.innerHeight;
  let scrollState = window.scrollY;
  let offset = 100; // If you want to start the load earlier than the bottom

  if (scrollState > windowHeight - offset) {
    this.currentView();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM