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

能不能把useTimeout升级一下? #2537

Open
npmstudy opened this issue Apr 26, 2024 · 6 comments
Open

能不能把useTimeout升级一下? #2537

npmstudy opened this issue Apr 26, 2024 · 6 comments
Labels

Comments

@npmstudy
Copy link

用法示意

import { useTimeout } from 'ahooks/useTimeout';

export default  () => {
  const [counter, setCounter] = useState(0)
  const [start, clear, isActive] = useTimeout(() => setCounter(counter + 1), 0, false);

  return (
    <div className="App" onClick={() => start()}>
      <h1 style={{border:'1px dashed'}}>点击开启定时器 {counter}</h1>
    </div>
  );
};

如果需要,我把pr和测试提上来。

@liuyib
Copy link
Collaborator

liuyib commented Apr 26, 2024

其实目前已经满足你这个使用场景了:

文档里有提到:useTimeout 的时间设置为 undefined 时会停止定时器

import React, { useState } from 'react';
import { useInterval } from 'ahooks';

export default () => {
  const [count, setCount] = useState(0);
  const [delay, setDelay] = useState<number | undefined>(1000);

  const isActive = delay !== undefined;
  const start = () => setDelay(1000);
  const pause = () => setDelay(undefined);
  const clear = useInterval(() => {
    setCount(count + 1);
  }, delay);

  return (
    <div>
      <button onClick={start}>start</button>
      <button onClick={pause}>pause</button>
      <button onClick={clear}>clear</button>
      <div>isActive: {`${isActive}`}</div>
      <div>count: {count}</div>
    </div>
  );
};

不过比较麻烦一些。可以考虑升级一下

@liuyib liuyib added question feature New feature or request labels Apr 26, 2024
@liuyib
Copy link
Collaborator

liuyib commented Apr 26, 2024

旧 API:

const clear = useTimeout(fn, delay);

新 API:

const {
  start,
  pause,
  clear,
  isActive,
} = useTimeout(fn, delay, {
  defaultActive: false
})
  • start: (delay?: number) => void
  • pause: () => void
  • clear: () => void
  • isActive: boolean

会引入 breaking change。看看大家的意见~

另外,@npmstudy 要不分享下你的使用场景?

@raotaohub
Copy link

目前useTimeout(fn, delay); 返回的仅仅是一个 clear 函数,如果要为以后迭代更丰富的功能,确实应该返回成对象,方便扩展。
是不是应该放到4.x去做这件事@liuyib

@liuyib
Copy link
Collaborator

liuyib commented Apr 30, 2024

目前useTimeout(fn, delay); 返回的仅仅是一个 clear 函数,如果要为以后迭代更丰富的功能,确实应该返回成对象,方便扩展。
是不是应该放到4.x去做这件事@liuyib

是的,破坏性更改。需要 v4 做

@npmstudy
Copy link
Author

npmstudy commented May 6, 2024

好的,这周搞定

@npmstudy
Copy link
Author

还有一些新增修改,比如start方法,需要把参数透传给具体fn。

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

No branches or pull requests

3 participants