Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[useThrottle] 组件渲染后在 wait 之前更新 state 不会立即更新 throttledValue #2483

Open
tjx666 opened this issue Feb 20, 2024 · 1 comment
Assignees

Comments

@tjx666
Copy link

tjx666 commented Feb 20, 2024

源码:

function useThrottle<T>(value: T, options?: ThrottleOptions) {
  const [throttled, setThrottled] = useState(value);

  const { run } = useThrottleFn(() => {
    setThrottled(value);
  }, options);

  // 在组件挂载时就更新了一次,导致 wait ms 内不会相应更新
  useEffect(() => {
    run();
  }, [value]);

  return throttled;
}

测试代码:

export default function Page() {
    const [value, setValue] = useState<string>('');
	// 将 wait 设置的长一点,当用户第一次输入时,需要等待 3000 ms 后才会更新,而且其实是因为 trailing 更新的
    const throttledValue = useThrottle(value, { wait: 3000, leading: true });

    return (
        <div>
            <input
                value={value}
                onChange={(e) => setValue(e.target.value)}
                placeholder="Typed value"
                style={{ width: 280 }}
            />
            <p style={{ marginTop: 16 }}>throttledValue: {throttledValue}</p>
        </div>
    );
}

解决方案:

function useThrottle<T>(value: T, options?: ThrottleOptions) {
    const [throttled, setThrottled] = useState(value);
    const isFirstTimeRunEffect = useRef<boolean>(true);
  
    const { run } = useThrottleFn(() => {
      setThrottled(value);
    }, options);
  
    useEffect(() => {
        if (!isFirstTimeRunEffect.current) {
            run();
        } 
		// 第一次 run Effect 时不 run 即可
		else {
            isFirstTimeRunEffect.current = false
        }
    }, [value]);
  
    return throttled;
  }

如果我说的没问题,我愿意 pr。

@tjx666 tjx666 changed the title [useThrottle] 组件渲染后在 wait 之前更新 state [useThrottle] 组件渲染后在 wait 之前更新 state 不会立即更新 throttledValue Feb 20, 2024
@hchlq
Copy link
Collaborator

hchlq commented Feb 28, 2024

提的没有问题,但是解决方案不太行。

但是要做的话,需要兼容和 lodash throttle 其他相关的 API,估计改动不小

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants