ts
箭头函数写泛型
const useFilters =
一定要将T exteds 一下才可以,因为不这样做,无法与 jsx 识别区分开来,有点无奈。
https://github.com/Microsoft/TypeScript/issues/4922
ts
https://zhuanlan.zhihu.com/p/214280582
灵活获取组件入口类型
常适用于库的作者未能描述正确入口的类型的情况。
不用导出,获取一个组件的类型:
import * as React from 'react';import { Button } from 'antd';type ButtonProps = React.ComponentProps<typeof Button>;
如果某个组件用泛型描述,通过添加一个泛型工具函数:
export interface Type<T> extends Function {new (...args: any[]): T;}type NumberSelectProps = React.ComponentProps<Type<Select<number>>>;
forceUpdate
在hook中,useState的dispatch可以触发rerender
所以可以利用其特性,配合 ref 进行自定义的数据更改后render:
/*** Execute code before next frame but async*/export function useLayoutState<State>(defaultState: State,): [State, (updater: Updater<State>) => void] {const stateRef = useRef(defaultState);const [, forceUpdate] = useState({});const lastPromiseRef = useRef<Promise<void>>(null);const updateBatchRef = useRef<Updater<State>[]>([]);function setFrameState(updater: Updater<State>) {updateBatchRef.current.push(updater);const promise = Promise.resolve();lastPromiseRef.current = promise;promise.then(() => {if (lastPromiseRef.current === promise) {const prevBatch = updateBatchRef.current;const prevState = stateRef.current;updateBatchRef.current = [];prevBatch.forEach(batchUpdater => {stateRef.current = batchUpdater(stateRef.current);});lastPromiseRef.current = null;if (prevState !== stateRef.current) {forceUpdate({});}}});}useEffect(() => () => {lastPromiseRef.current = null;},[],);return [stateRef.current, setFrameState];}
