如何防止反应本机中的 Algolia 即时搜索初始加载?

How to prevent initial load from Algolia instant search in react native?

我有一个用户集合,我想在用户输入时查询它,但是当我切换到“搜索用户”屏幕时,即使搜索为空,所有用户都已填充在屏幕上。

如何防止这种情况发生并仅在 he/she 在搜索框中输入时才将结果发送给客户端??

我找到了一些其他链接和资源,但它们要么太旧,对我来说难以理解,要么使用 React 而不是 React Native

我是一名初级开发人员,如果您能详细说明解决方案,那就太好了。

这是我的代码:

SEARCH_USER.JS:

import React, {Component} from 'react';
import {
  View,
  Text,
  TextInput,
  Alert,
  FlatList,
  ActivityIndicator,
} from 'react-native';


import firestore from '@react-native-firebase/firestore';
import algoliasearch from 'algoliasearch';
import {
  InstantSearch,
  connectSearchBox,
  connectInfiniteHits,
} from 'react-instantsearch-native';
import PropTypes from 'prop-types';
import InfiniteHits from '../components/Algolia Components/InfiniteHits';



class SearchAddBuddyScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      value: null,
    };
  }


  searchClient = algoliasearch(
    '########',
    '####################',
  );

  render() {
    return (
      <View>
        <SecondaryHeader secondaryHeaderTitle="Add Buddies" />
        <InstantSearch
          searchClient={this.searchClient}
          indexName="prod_USERSCOLLECTION"
          onSearchStateChange={searchState =>
            console.log('=====> ', searchState)
          }>
          <ConnectedSearchBox />
          <InfiniteHits navigation={this.props.navigation} />
        </InstantSearch>
      </View>
    );
  }
}

class SearchBox extends Component {
  render() {
    console.log('Connected Search Box called');
    return (
      <View
        style={[
          textInput.generalTextInput,
          {
            marginBottom: 24,
            alignSelf: 'center',
            justifyContent: 'center',
          },
        ]}>
        <TextInput
          placeholderTextColor="#333647"
          style={[textInput.generalTextInput, {alignSelf: 'center'}]}
          onChangeText={text => this.props.refine(text)}
          value={this.props.currentRefinement}
          placeholder={'Search'}
          clearButtonMode={'always'}
          spellCheck={false}
          autoCorrect={false}
          autoCapitalize={'none'}
        />
      </View>
    );
  }
}

SearchBox.propTypes = {
  refine: PropTypes.func.isRequired,
  currentRefinement: PropTypes.string,
};

const ConnectedSearchBox = connectSearchBox(SearchBox);
export default SearchUserScreen;

InfiniteHits.js:

import React, {Component} from 'react';
import {StyleSheet, Text, View, FlatList} from 'react-native';
import {connectInfiniteHits} from 'react-instantsearch-native';
import AddFriendComponent from '../AddFriend';

class InfiniteHits extends Component {
  constructor(props) {
    super(props);

    this.navigation = this.props.navigation;
  }
  _renderItem = ({item}) => {
    return (
      <AddFriendComponent
        username={item.username}
        fullName={item.fullName}
        onPressUserProfile={() =>
          this.props.navigation.navigate('UserProfile', {profileId: item.uid})
        }
      />
    );
  };

  render() {
    return (
      <FlatList
        data={this.props.hits}
        keyExtractor={item => item.objectID}
        // ItemSeparatorComponent={() => <View style={styles.separator} />}
        onEndReached={() => this.props.hasMore && this.props.refine()}
        renderItem={this._renderItem}
      />
    );
  }
}
export default connectInfiniteHits(InfiniteHits);

阅读更多内容后 material 我发现了这个 https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-requests/react/

并对我的代码进行了以下更改并成功。


conditionalQuery = {
    search(requests) {
      if (
        requests.every(({params}) => !params.query) ||
        requests.every(({params}) => params.query === ' ') ||
        requests.every(({params}) => params.query === '  ') ||
        requests.every(({params}) => params.query === '   ')
      ) {
        // Here we have to do something else
        console.log('Empty Query');
        return Promise.resolve({
          results: requests.map(() => ({
            hits: [],
            nbHits: 0,
            nbPages: 0,
            processingTimeMS: 0,
          })),
        });
      }
      const searchClient = algoliasearch(
        '########',
        '###################',
      );
      return searchClient.search(requests);
    },
  };
  render() {
    return (
      <View>
        <SecondaryHeader secondaryHeaderTitle="Add Buddies" />
        <InstantSearch
          searchClient={this.conditionalQuery}
          indexName="prod_USERSCOLLECTION"
          onSearchStateChange={searchState =>
            console.log('=====> ', searchState)
          }>
          <ConnectedSearchBox />
          <InfiniteHits navigation={this.props.navigation} />
        </InstantSearch>
      </View>
    );
  }

此解决方案仍可针对键入的空格进行改进,但我不知道该怎么做。