如何在 React Native 中实现搜索 API

how to implement search API in react native

我有这样的文本输入

  <CustomInput
            value={searchInput}
            onChangeText={(e) => func(e)}
            mainStyle={{ width: "81%" }}
            placeholder="Search"
          />

现在我有这样的功能了

const func = async (searchText) => {
    setSearchInput(searchText);
    searchAPI();
  };

这是我的API调用代码

const searchAPI = async () => {
    try {
      const data = new FormData();
      data.append("string_search", searchInput);
      setActivityIndicatorVal(true);
      let response = await fetch(
        "APILINK",
        {
          method: "POST",
          body: data,
          header: {
            "Content-Type": "multipart/form-data",
          },
        }
      );
      var json = await response.json();
      if (json.status == 1) {
        setActivityIndicatorVal(false);
        setList(json.data);
      } else {
        setActivityIndicatorVal(false);
        console.log("Error");
        getServiceList();
      }
    } catch (e) {
      setActivityIndicatorVal(false);

      Alert.alert("Error", "Error Massage : " + e, [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel",
        },
        { text: "OK", onPress: () => console.log("OK Pressed") },
      ]);
      return;
    }
  };

现在我的问题是,当我开始在文本框中输入内容时,结果正在快速显示并正确显示。但是我通过按下键盘按钮从文本输入中删除所有文本。然后它应该显示所有结果。但它只显示我最近通过后退键盘按钮删除的那个关键字。请帮忙谢谢。

当用户输入时,searchAPI 由于 React 状态更新和组件渲染的工作原理,收到旧的输入值。

试试这个重构。

const func = async (searchText) => {
    setSearchInput(searchText);
  
  //This function execute before component rerender.
  // always pass input text value not rely on state value
    searchAPI(searchText);
  };

然后searchAPI

const searchAPI = async (searchQuery) => {
    try {
      const data = new FormData();
      data.append("string_search", searchQuery);
      setActivityIndicatorVal(true);
      let response = await fetch(
        "APILINK",
        {
          method: "POST",
          body: data,
          header: {
            "Content-Type": "multipart/form-data",
          },
        }
      );
      var json = await response.json();
      if (json.status == 1) {
        setActivityIndicatorVal(false);
        setList(json.data);
      } else {
        setActivityIndicatorVal(false);
        console.log("Error");
        getServiceList();
      }
    } catch (e) {
      setActivityIndicatorVal(false);

      Alert.alert("Error", "Error Massage : " + e, [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel",
        },
        { text: "OK", onPress: () => console.log("OK Pressed") },
      ]);
      return;
    }
  };

您可以通过去抖动搜索查询并仅在用户完成搜索查询键入时查询数据库来改善用户体验并节省服务器资源。

// Utilitiy debounce function

function debounce(fn, wait) {
  var timeout;
  return function () {
    var ctx = this,
      args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      fn.apply(ctx, args);
    }, wait || 500);
  };
}

const debouncedSearch = debounce(func, 500);

<CustomInput
    onChangeText={debouncedSearch}
    mainStyle={{ width: "81%" }}
    placeholder="Search"
  />