React Native Fetch 异步

React Native Fetch asynchronous

我很难真正理解异步行为。我正在调用日语数据库,但由于异步行为,我的调用比用户输入晚了一步。例如,用户输入字母 G 不会有任何响应,直到用户输入 Go。然后,当用户排除 Go 的结果时,我的应用程序将发送一个查询字母 G 的请求。希望这有点道理。

这是我进行异步调用的地方。

sendData(){
        fetch('http://jisho.org/api/v1/search/words?keyword='+this.state.wordLookUp).then((dictionary) => {

                return dictionary.json();
            }).then((dictionary) => {
                console.log(dictionary);
                this.setState({
                    dictionary:dictionary.data,
                    loading:false
                })

            }).done((dictionary)=>{
                console.log(this.state.dictionary);


            });


    }

这里是我向用户显示结果的地方

renderList(){
     if(!this.state.wordLookUp.length){
        this.state.dictionary = null;
     }

     if(!this.state.dictionary){    
      return(
        <View>
        <Text>loading</Text>
        </View>
        )
     }else{

     return this.state.dictionary.map(words => 
            <ScrollView>
            <Text>{words.senses[0].english_definitions}  {words.japanese[0].reading}</Text>
             </ScrollView>

         );
     }
    }

我的渲染函数在这里:

render(){   
     return(
     <View>
     <Header/>
       <Fumi            
        label={'Add Englishword....'}
        iconClass={FontAwesomeIcon}
        iconName={'pencil'}
        iconColor={'#f95a25'}
        onSubmitEditing={(wordLookUp) => {

            this.sendData();    
        dismissKeyboard(); 
        }}
        onChangeText={(wordLookUp) =>{
            this.setState({wordLookUp});
            console.log(wordLookUp);
            this.sendData(); 
            this.renderList();
        }}

       />
     {this.renderList()}
     </View>
    )   

    }
}

这是启发我设计的字典。 http://www.nihongodict.com/w/15758/ichiranhyou/

提前致谢。

我的建议是等到用户完成输入要搜索的单词或字母。例如,一种常见的方法是将函数排队 300 毫秒,然后如果在 300 毫秒内再次调用此函数,执行将再次延迟 300 毫秒。这样,如果用户打字速度非常快,您就不会为每次击键请求服务器,而是为最终结果请求服务器。

这是一个示例,说明如何创建一个每 X 毫秒运行一次的函数,如果对该函数进行了新调用,则会取消之前的调用并将新调用排队。

function createBuffered(callback, buffer) {
  var timerId;

  return function(...params) {
    if (timerId) {
      clearTimeout(timerId);
    }

    timerId = setTimeout(function(){
      callback.apply(this, params);
    }, buffer);
  };
}

首先你必须创建一个函数缓冲函数,然后在每次击键时调用它,它会自动延迟执行。这是有关如何使用它的示例。

class Testing extends Component {
  state = {
    query: '',
    fetch: '',
  };

  componentWillMount() {
      // This function will be buffered for 300ms
    this.fetchData = createBuffered((query) => {
      // You should make your fetch request here.
      this.setState({
         fetch: query,
      });
    }, 300);
  }

  load(query) {
    // This will be called constantly but nothing will happen until
    // 300ms without activity on the input field
    this.fetchData(query);
  }

  setQuery = (event) => {
    // Just updating the state to save the input
    const query = event.target.value;
    this.setState({
      query,
    });
    // Set the queue
    this.load(query);
  }

  render() {
    const { fetch, query } = this.state;

    return (
      <View>
        <Text>After 300ms, search for: {fetch}</Text>
        <TextInput value={query} onChange={this.setQuery} />
      </View>
    );
  }
}

祝你好运!!

编辑:这是 reactjs 中的一个 运行 示例,只有 JSX 有点不同:https://jsfiddle.net/crysfel/fo7q6wzd/