React Native - 如何在执行函数之前处理 TextInput onChangeText 事件以等待?

fli*_*lix 5 javascript textinput react-native

我有一个在 React Native 中使用文本输入的搜索功能,但是搜索需要调用一个 API,所以我想onChangeText在用户完成输入 2 秒后保持运行,

我试过使用setIntervalsetTimeout但这些都不起作用,

这是我试过的代码:

<TextInput
  placeholder="search"
  onChangeText={(text) => {
    setTimeout(() => {
      console.log(text)
      console.log("Kepanggil TimeOUTNYAA")
      params.onSearchText(text)
    }, 2000);
  }
}

//function onSearchText

onSearchText(searchText){
  this.setState({text:searchText},()=>{
    this._loadMore() // here's a function to call the API
  })
}
Run Code Online (Sandbox Code Playgroud)

实际行为:

当我键入amTextInput日志显示我:

实际的

预期行为:

我希望日志 显示我am aam

有可能做到吗?

Sad*_*ori 5

您应该在设置新超时之前清除旧超时

<TextInput
    placeholder="search"
    onChangeText={(text) => {
        if(this.searchWaiting)
            clearTimeout(this.searchWaiting);
        this.searchWaiting = setTimeout(() => {
            this.searchWaiting = null;
            console.log(text);
            console.log("Kepanggil TimeOUTNYAA")
            params.onSearchText(text)
        }, 2000);
    }}
/>
Run Code Online (Sandbox Code Playgroud)


Kis*_*Oza -1

你根本不能在它的回调函数setTimeOut上放置任何类型的代码,这意味着在事件触发后你收到了一些在你的场景中无用的代码(bcz事件被触发并且API被调用)。onChangeTexttextonSearchText

你可以做的是在你的onSearchText函数中你可以有条件地返回,text就像如果文本长度大于2或3然后只调用.LikeAPI这样:

onSearchText(searchText){
  if(searchText.length > 3){
      this.setState({text:searchText},()=>{
         this._loadMore() // here's a function to call the API
      })
  }
}
Run Code Online (Sandbox Code Playgroud)