onMouseDown不会触发useEffect

时间:2020-04-03 16:08:31

标签: reactjs ionic-framework

如果用户按下按钮,则每500毫秒调用一次函数,以尝试实现可拖动的电平表。但是,由于某些原因,useEffect()仅在释放按钮时才触发,而我没有得到所需的效果。

这是代码的相关部分:

import React, { useContext, useEffect, useCallback, useState, useRef } from 'react';
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonToggle, IonList, IonItem, IonLabel, IonItemDivider } from '@ionic/react';
import useLongPress from './useLongPress';
import './LightController.css';
import { AppContext } from './../AppContextProvider';

export interface InterfaceLamp {
  id?: number,
  brightness: number,
  turnedOn: boolean,
}

const LightController: React.FC<InterfaceLamp> = (props) => {
  const { state, dispatch } = useContext(AppContext);

  const [isMouseDown, setMouseDown] = useState(false);
  const [interval, confInterval] = useState();


  useEffect(() => {
    if (isMouseDown) {
      let timeOut = setInterval(getPercentage, 500);
      confInterval(timeOut);
    } else {
      clearInterval(interval);
    }
    return () => {
      clearInterval(interval);
    };
  }, [isMouseDown]);

  const getPercentage = () => {
    console.log('percentage')
  }

  return (
    <div className="c-light">
      <p>brightness</p>
      <div className="c-light__meter__wrapper"
        onMouseDown={(e) => setMouseDown(true)}
        onMouseUp={(e) => setMouseDown(false)}
      >
        <div className="c-light__meter">
        </div>
        <div className="c-light__meter__value">
          {props.brightness}
        </div>
      </div>
    </div>
  );
};

export default LightController;

有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

useDebounce.ts

import { useState, useEffect } from 'react';

function useDebounce<T>(
  initialValue: T,
  time: number
): [T, T, React.Dispatch<T>] {
  const [value, setValue] = useState<T>(initialValue);
  const [debouncedValue, setDebouncedValue] = useState<T>(initialValue);

  useEffect(() => {
    const debounce = setTimeout(() => {
      setDebouncedValue(value);
    }, time);
    return () => {
      clearTimeout(debounce);
    };
  }, [value, time]);

  return [debouncedValue, value, setValue];
}

LightController.ts

const [debouncedMouseDown, isMouseDown, setMouseDown] = useDebounce<boolean>(false, 500);

useEffect(() => {
  // do something
}, [debouncedMouseDown])

// rest omitted

Nick Scialli

建议的优雅方法

另外,请参见use-lodash-debounce