WbwLookup.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { useEffect, useRef } from "react";
  2. import { useAppSelector } from "../../../hooks";
  3. import { add, updateIndex, wordIndex } from "../../../reducers/inline-dict";
  4. import { get } from "../../../request";
  5. import type { IApiResponseDictList } from "../../../api/Dict";
  6. import store from "../../../store";
  7. interface IWidget {
  8. run?: boolean;
  9. words?: string[];
  10. delay?: number;
  11. }
  12. const WbwLookup = ({ words, run = false, delay = 300 }: IWidget) => {
  13. const inlineWordIndex = useAppSelector(wordIndex);
  14. const intervalRef = useRef<number | null>(null); //防抖计时器句柄
  15. useEffect(() => {
  16. // 监听store中的words变化
  17. if (run && words && words.length > 0) {
  18. // 开始查字典
  19. intervalRef.current = window.setInterval(lookup, delay, words);
  20. } else {
  21. stopLookup();
  22. }
  23. return () => {
  24. // 组件销毁时清除计时器
  25. clearInterval(intervalRef.current!);
  26. };
  27. }, [run, words]);
  28. /**
  29. * 停止查字典计时
  30. * 在两种情况下停止计时
  31. * 1. 开始查字典
  32. * 2. 防抖时间内鼠标移出单词区
  33. */
  34. const stopLookup = () => {
  35. if (intervalRef.current) {
  36. window.clearInterval(intervalRef.current);
  37. intervalRef.current = null;
  38. }
  39. };
  40. /**
  41. * 查字典
  42. * @param word 要查的单词
  43. */
  44. const lookup = (words: string[]) => {
  45. stopLookup();
  46. //查询这个词在内存字典里是否有
  47. const searchWord = words.filter((value) => {
  48. if (inlineWordIndex.includes(value)) {
  49. //已经有了
  50. return false;
  51. } else {
  52. return true;
  53. }
  54. });
  55. if (searchWord.length === 0) {
  56. return;
  57. }
  58. const url = `/v2/wbwlookup?word=${searchWord.join()}`;
  59. console.info("api request", url);
  60. get<IApiResponseDictList>(url).then((json) => {
  61. console.debug("api response", json);
  62. //存储到redux
  63. store.dispatch(add(json.data.rows));
  64. store.dispatch(updateIndex(searchWord));
  65. });
  66. console.log("lookup", searchWord);
  67. };
  68. return <></>;
  69. };
  70. export default WbwLookup;