简体   繁体   English

提交时反应原生元素搜索栏

[英]React native elements search bar on submit

when im typing on the search bar and press submit the flatlist should render again making an api request but it doesnt The method makeRequest is not called in updateSearch and i dont know why当我在搜索栏上输入并按提交时,flatlist 应该再次呈现,发出 api 请求,但它没有在 updateSearch 中没有调用 makeRequest 方法,我不知道为什么

 <SearchBar
     placeholder="Type something here...."
     onChangeText={this.updateSearch}
     value={search}
 />

updateSearch = search => {
    this.setState({ search }, this.makeRequest);    
  };

makeRequest =  () => {

    const { page, search } = this.state;

    const apiKey = 'a40093f0-53ec-11ea-850a-fbf5bb8990e'

    const url =
            `https://api.harvardartmuseums.org/object?apikey=${apiKey}` +
            `&title=${search}`+
            `&fields=objectnumber,dated,century,division,primaryimageurl,title` +
            `&sort=totalpageviews` +
            `&page=${page}` +
            `&size=44` +
            `&hasimage=1` +
            `&sortorder=desc`;
    setTimeout(() => {
      fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        const results = processExhibit(responseJson);
        this.setState({
          isLoading: false,
          dataSource: [...this.state.dataSource,...results],
          refreshing: false
        });

      });
    }, 1500);

  }


https://snack.expo.io/@overhype/885549 https://snack.expo.io/@overhype/885549

to avoid repeatly call API when user typing, using onSubmitEditing which fired when user click submit on soft keyboard避免在用户键入时重复调用 API,使用 onSubmitEditing 当用户在软键盘上单击提交时触发

const [keywords, setKeywords] = React.useState('')

<Searchbar
  placeholder="Search Products ..." 
  onChangeText={(val) => { setKeywords(val) }}
  onSubmitEditing={()=>console.log(`User typed ${keywords}`)}
  value={keywords} 
/>

or replaced with或替换为

onSubmitEditing={({nativeEvent})=>console.log(nativeEvent.text)}

Please remove setTimeout as it might show results that are not related to what the user has typed.请删除setTimeout因为它可能会显示与用户输入的内容无关的结果。 if you want to make a request with each key press just call makeRequest in updateSearch .如果您想通过每次按键发出请求,只需在updateSearch调用makeRequest Try adding min character length to minimise making requests with each key press.尝试添加最小字符长度以最小化每次按键时发出的请求。

updateSearch = search => {
  this.setState({ search }, () => this.makeRequest());
};

makeRequest = () => {
  const { page, search, minLength } = this.state;

  if (search && search.length < minLength) {
    return;
  }

  const url =
    `https://api.harvardartmuseums.org/object?apikey=${apiKey}` +
    `&title=${search}` +
    `&fields=objectnumber,dated,century,division,primaryimageurl,title` +
    `&sort=totalpageviews` +
    `&page=${page}` +
    `&size=44` +
    `&hasimage=1` +
    `&sortorder=desc`;

  fetch(url)
    .then(response => response.json())
    .then(responseJson => {
      console.log(responseJson);
      const results = processExhibit(responseJson);
      this.setState({
        isLoading: false,
        dataSource: [...this.state.dataSource, ...results],
        refreshing: false,
      });
    });
};

Hi please try with below嗨,请尝试以下

import React, { Component } from 'react';
import { View, Text, FlatList, Image } from 'react-native';
import PropTypes from 'prop-types';
import { Card, SearchBar } from 'react-native-elements';

const apiKey = 'a40093f0-53ec-11ea-850a-fbf5bb8990ef';

 const processExhibit = results => {
  const processed = 
    results.records.map(r => ({
      ...r,
      id: r.objectnumber
    }))
  return processed;
};

export default class FetchExample extends Component {

  constructor (props: {}) {
    super(props);

    this.state = {
        page: 1,
        isLoading: true,
        dataSource: [],
        refreshing: false,
        search: 'cat'
    };
  }

  componentDidMount () {
    this.makeRequest();
  }

  makeRequest =  () => {

    const { page, search } = this.state;
    const url =
            `https://api.harvardartmuseums.org/object?apikey=${apiKey}` +
            `&title=${search}`+
            `&fields=objectnumber,dated,century,division,primaryimageurl,title` +
            `&sort=totalpageviews` +
            `&page=${page}` +
            `&size=44` +
            `&hasimage=1` +
            `&sortorder=desc`;
    setTimeout(() => {
      fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        const results = processExhibit(responseJson);
        this.setState({
          isLoading: false,
          dataSource: results,
          refreshing: false
        });

      });
    }, 1500);
  }

  renderItem = ({item, index}) => {

    if (!item) {
      return null
    }

    return (
      <View >
        <Card
          title={item.title}
          image={{uri: item.primaryimageurl}}>
          <Text style={{marginBottom: 10}}>
            Made in {item.dated}
          </Text>
       </Card>
      </View>
    );
  }

  keyExtractor = (item, index) => {
    return index.toString();
  }

  updateSearch = search => {
    this.setState({ search });  
    this.makeRequest(search);
  };

  handleLoadMore = () => {
    this.setState({ page: this.state.page + 1}, this.makeRequest)
  }

  handleRefresh = () => {

    this.setState({
      page: 1,
      refreshing: true,

    }),
    () =>
      this.makeRequest();
  }

  render () {
    const { search } = this.state;
    return (

      <View style={{flex: 1}}>

        <SearchBar
            placeholder="Type something here...."
            onChangeText={this.updateSearch}
            value={search}
        />
        <FlatList
          data={this.state.dataSource}
          keyExtractor={this.keyExtractor}
          renderItem={this.renderItem}
          refreshing={this.state.refreshing}
          onEndReached={this.handleLoadMore}
          onEndThreshold={100}
        />
      </View>
    );
  }
}

Snack : https://snack.expo.io/Sk!aRjR78小吃: https ://snack.expo.io/Sk! aRjR78

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

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