【问题标题】:Throttle with lodash isn't throttling using ReactJS使用 lodash 的节流不使用 ReactJS 进行节流
【发布时间】:2021-11-30 22:15:59
【问题描述】:

所以我有这个代码

import React, { createRef, useEffect, useCallback, useState } from 'react';
import { throttle } from 'lodash';
import { setProgress } from '../../helpers/markersApi';

const EXECUTE_EVERY_THIRTY_SECONDS = 30 * 1000; 
const throttledSetProgress = throttle(setProgress, EXECUTE_EVERY_THIRTY_SECONDS);

const Player = ({}) => {

  const updateProgress = (playerPosition, asset, immediateUpdate = false) => {
    if (asset.type !== 'EPG_PROGRAM') {
      const {
        id, episode,
      } = asset;
      const type = (episode && episode.episodeNumber) ? 'episode' : 'movie';

      if (immediateUpdate) {
        console.log('IMMEDIATE');
        // Cancel possible future invocations and set progress immediately
        throttledSetProgress.cancel();
        setProgress(id, playerPosition, type);
      } else {
        throttledSetProgress(id, playerPosition, type);
      }
    }
  };

  useEffect(() => {
    updateProgress(position, playerAsset);
  }, [position, playerAsset]);
}

问题是节流不起作用,因为每次调用 useEffect 时它都会运行 setProgress。有什么想法吗?

【问题讨论】:

  • 你能提供整个组件吗,好像你在组件外使用了useEffect。

标签: reactjs lodash throttling


【解决方案1】:

节流函数在重新渲染之间应该保持不变,这意味着我们必须使用 React 的 UseCallback 函数。这可以通过更改 throttledSetProgress 来实现:

const throttledSetProgress = throttle(setProgress, EXECUTE_EVERY_THIRTY_SECONDS);

到这里:

const throttledSetProgress = useCallback(
  throttle(setProgress, EXECUTE_EVERY_THIRTY_SECONDS),
  [],
);

(别忘了从 'react' 导入 useCallback)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2020-12-18
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多