-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(shared): 新增 useStateWithTrailClear 带尾部自动清理的状态
- Loading branch information
1 parent
b2f9033
commit 0dc1bef
Showing
2 changed files
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import React, { useEffect, useState } from 'react'; | ||
|
||
/** | ||
* 带后续清理的状态 | ||
* | ||
* 每当设置一个值,下一次 Effect 就会把它重置为 undefined, | ||
* 也就是说会触发 3 次 effect: | ||
* 1. 外部依赖状态更新 | ||
* 2. 依据外部状态更新内部状态 | ||
* 3. 内部状态恢复为 undefined | ||
* | ||
* 类似电子打火机的点火装置,点着了气体之后接下来就与点火器无关且可以关掉了。 | ||
*/ | ||
export function useStateWithTrailClear<T>( | ||
visible: T | undefined, | ||
): ReturnType<typeof React.useState<T>> { | ||
const [state, setState] = useState<typeof visible>(); | ||
|
||
useEffect(() => { | ||
state !== undefined && setState(undefined); | ||
}, [state]); | ||
useEffect(() => setState(visible), [visible]); | ||
|
||
return [state, setState]; | ||
} |