Реагируйте на поиск по Native & Firebase - PullRequest
0 голосов
/ 16 ноября 2018

Я пытаюсь использовать FireBase и выполнить поиск.Проблема, которую я имею, когда я набираю текст поиска, данные списка не обновляются.

Ниже приведен код, который я придумал

componentDidMount() {
    this.setState({loading: true});

    var merchants = new Array;

    merchantsRef.once('value').then((snapshot) => {
      snapshot.forEach((child) => {
        merchants.push({
          id: child.val().id,
          type:  child.val().type,
          attributes: {
            coming_soon: child.val().attributes.coming_soon,
            featured_image_url: child.val().attributes.featured_image_url,
            has_locations: child.val().attributes.has_locations,
            highlight: child.val().attributes.highlight,
            logo_url: child.val().attributes.logo_url,
            main_image_url: child.val().attributes.main_image_url,
            name: child.val().attributes.name,
            offer_active: child.val().attributes.offer_active,
            offer_cta_title: child.val().attributes.offer_cta_title,
            offer_ends_at: child.val().attributes.offer_ends_at,
            offer_starts_at: child.val().attributes.offer_starts_at,
            offer_teaser: child.val().attributes.offer_teaser,
            offer_terms: child.val().attributes.offer_terms,
            offer_text: child.val().attributes.offer_text,
            offer_url: child.val().attributes.offer_url,
            permalink: child.val().attributes.permalink,
            shop_url: child.val().attributes.shop_url,
          },
          _key: child.key
        })
      })
      this.setState({
        data: merchants,
        loading: false,
      })
      // console.log(this.state.data)
    }).catch((error) => {
      console.log('Error fetching retailer data:', error)
    })

  }

  searchFilterFunction = text => {

    merchantsRef.orderByChild('name').startAt(text.toString()).on('value', function(child) {
        console.log(child.val());
    });

  };

  _renderEmpty = () => {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <ActivityIndicator />
      </View>
    )
  }

  _renderItem = ({item}) => (
    <MerchantRow data={item} />
  )

  _keyExtractor = (item, index) => item._key;

  render() {
    if (this.state.loading) {
      console.log("Loading")
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator
            animating
            size="large"
          />
          <Text>Fetching shops...</Text>
        </View>
      )
    }
    return (
      <View style={styles.container}>
        <SearchBar
          placeholder='Search for retailers...'
          containerStyle={{backgroundColor: Colors.blue, borderTopWidth: 0, borderBottomWidth: 0}}
          inputStyle={{backgroundColor: Colors.snow}}
          onChangeText={text => this.searchFilterFunction(text)}
          autoCorrect={false}
        />
        <ScrollView style={styles.container}>
          <FlatList
            data={this.state.data}
            renderItem={this._renderItem.bind(this)}
            keyExtractor={this._keyExtractor}
            initialNumToRender={9}
            ItemSeparatorComponent={this._renderSeparator}
            removeClippedSubviews={false}
            ListEmptyComponent={this._renderEmpty}
          />
        </ScrollView>
      </View>
    )
  }

1 Ответ

0 голосов
/ 16 ноября 2018

@ Paul'Whippet'McGuane, приятно знать.Это вероятно, потому что контекст this не определен.Чтобы сохранить контекст ключевого слова this, вы можете изменить searchFilterFunction следующим образом:

 searchFilterFunction = text => {
    const that = this;
    merchantsRef.orderByChild('name').startAt(text.toString()).on('value', function(child) {
        console.log(child.val());
        const val = child.val();
        that.setState({ data: val });
    });
  };
...