@@ -21,11 +21,45 @@ export interface IUseListOptions {
2121 immediate ?: boolean ;
2222}
2323
24+ /**
25+ * 返回值
26+ */
27+ export interface UseListResponseState <
28+ T extends Record < string , any > ,
29+ P extends Record < string , any >
30+ > {
31+ /**
32+ * 请求是否执行中
33+ */
34+ loading : boolean ;
35+ /**
36+ * 请求的相关参数以及结果数据的总数
37+ */
38+ params : P & { total : number } ;
39+ /**
40+ * 错误信息
41+ */
42+ error ?: Error ;
43+ /**
44+ * 返回的数据
45+ */
46+ data : T [ ] ;
47+ mutate : ( params ?: Partial < P > | ( ( prev : P ) => P ) , options ?: IMutateOptions ) => void ;
48+ /**
49+ * 清空所有数据和状态
50+ */
51+ clear : ( ) => void ;
52+ /**
53+ * 清空数据
54+ */
55+ clearData : ( ) => void ;
56+ }
57+
2458export default function useList < T extends Record < string , any > , P extends Record < string , any > > (
2559 fetcher : Fetcher < T , P > ,
2660 initialParams : P | ( ( ) => P ) ,
2761 rawOptions : IUseListOptions = { immediate : true }
28- ) {
62+ ) : UseListResponseState < T , P > {
2963 const [ error , setError ] = useState < Error | undefined > ( undefined ) ;
3064 const [ data , setData ] = useState < T [ ] > ( [ ] ) ;
3165 const [ total , setTotal ] = useState ( 0 ) ;
@@ -62,20 +96,22 @@ export default function useList<T extends Record<string, any>, P extends Record<
6296
6397 if ( nextOptions . revalidate ) {
6498 if ( nextOptions . clearData ) {
65- setData ( [ ] ) ;
66- setTotal ( 0 ) ;
67- setError ( undefined ) ;
99+ clearData ( ) ;
68100 }
69101 performFetch ( tmp ) ;
70102 }
71103 } ;
72104
73- const clear = ( ) => {
105+ const clearData = ( ) => {
74106 setData ( [ ] ) ;
75107 setTotal ( 0 ) ;
108+ setError ( undefined ) ;
109+ } ;
110+
111+ const clear = ( ) => {
112+ clearData ( ) ;
76113 setParams ( initialParams ) ;
77114 setLoading ( false ) ;
78- setError ( undefined ) ;
79115 } ;
80116
81117 useEffect ( ( ) => {
@@ -84,5 +120,5 @@ export default function useList<T extends Record<string, any>, P extends Record<
84120 }
85121 } , [ ] ) ;
86122
87- return { loading, params : { ...params , total } , error, data, mutate, clear } ;
123+ return { loading, params : { ...params , total } , error, data, mutate, clear, clearData } ;
88124}
0 commit comments