簡體   English   中英

React / TS:油門 function 但也設置 state

[英]React / TS: Throttle function but also set state

我有一個 React 功能組件。 有一個input字段,其value是使用useState設置的。 我有一個簡單的標准function throttle(callback: Function, delay = 1000)

要求:

  1. 通過onChange事件處理程序設置搜索詞(狀態)。
  2. 限制回調 (search()) function 調用。

我可以做一個,但不能兩個都做。 一邊用頭撞牆。

鏈接到代碼沙箱

我究竟做錯了什么?

謝謝你。

(僅供參考,我對去抖動不感興趣。)

使用useRef存儲 shouldWait 的值應該是shouldWait的方式。 此外,可以在throttle useCallback上使用 useCallback 來記憶它。

import React, { ChangeEvent, useState, useMemo, useRef, useCallback } from "react";

/*
Requirements:
1. Set search term (state), 
2. Throttle the callback (search()) function call.

There are two functions that should be interesting, both onChange handlers: 
 * handleOnChange (Does not satisfy Requirement 2)
 * throttledOnChangeHandler (Does not satisfy Requirement 1)
*/
export const Searchbox: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const shouldWait = useRef<boolean>(false);

  const throttle = useCallback((callback: Function, delay = 1000, ...args: any[]) => {
      if (shouldWait.current) return;

      callback(...args);
      shouldWait.current = true;

      setTimeout(() => {
        shouldWait.current = false;
      }, delay);
  }, []);

  function search() {
    console.log(new Date().getSeconds())
    console.log("Searching term:", searchTerm);
  }

  const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
    throttle(search);
    setSearchTerm(e.target.value);
  };

  return (
    <div>
      <h1>Search!</h1>
      <input
        type="text"
        placeholder="Blah!"
        value={searchTerm}
        onChange={handleOnChange}
      />
    </div>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM