本文介绍了如何在反应中使用 useDebounce 搜索功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在搜索功能中搜索用户时,我尝试使用 useDebounce.在这种情况下如何添加 useDebounce?

I am trying to use useDebounce when user search a user in search function. How can I add useDebounce in this situation?

import { useDebounce } from "use-debounce";
const [searchQuery, setSearchQuery] = useState("");
const [invitees, setInvitees] = useState([]);

  const handleChange = (event) => {
    event.preventDefault();
    setSearchQuery(event.target.value);
  };

  const getUserToInvite = async () => {
    const res = await axios.get(
      `/api/v1/search/users/invite/${searchQuery}/${teamId}`
    );
    setInvitees(res.data[0]);
    setShowInvitees(!showInvitees);
  };

  useEffect(() => {
    if (searchQuery === "") {
      setInvitees([]);
    }

    if ((searchQuery || "").length >= 2) {
      getUserToInvite();
    }
  }, [searchQuery]);


          <input
            className="invitees--search_input"
            type="text"
            name="name"
            onChange={handleChange}
            placeholder="Name"
            aria-label="Search bar"
            pattern="^[a-zA-Z0-9 ]+"
            required
          />

你如何在 React.js 中执行去抖动?

How do you perform debounce in React.js?

推荐答案

我认为您可以通过简单地消除该值来解决这个问题.所以像

I think you can handle that by simply debouncing the value. So something like

const [searchQuery, setSearchQuery] = useState("");
const debouncedSearchQuery = useDebounce(searchQuery, 500)

useEffect(() => {
    if (debouncedSearchQuery === "") {
      setInvitees([]);
    }

    if ((debouncedSearchQuery || "").length >= 2) {
      getUserToInvite();
    }
  }, [debouncedSearchQuery]);

如果您希望对回调进行去抖动,那就有点不同了.但是 use-debounce 文档很好地解释了它!https://github.com/xnimorz/use-debounce#debounced-callbacks

If you are looking to debounce the callback, that is a little different. But the use-debounce docs do a great way of explaining it!https://github.com/xnimorz/use-debounce#debounced-callbacks

这篇关于如何在反应中使用 useDebounce 搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 02:30