1
1
import "setimmediate" ;
2
2
import { useState , useEffect , useDebugValue } from "react" ;
3
- import { CHANGE } from "reshow-flux-base" ;
4
3
import { useMounted } from "reshow-hooks" ;
5
4
import { T_TRUE , T_FALSE } from "reshow-constant" ;
5
+ import { CHANGE } from "reshow-flux-base" ;
6
6
7
7
import getStores from "./getStores" ;
8
8
@@ -26,53 +26,51 @@ const handleShouldComponentUpdate = ({
26
26
} ;
27
27
} ;
28
28
29
- const useConnect = ( options ) => ( props ) => {
30
- const {
31
- calculateState,
32
- shouldComponentUpdate,
33
- displayName = "useConnect" ,
34
- } = options || { } ;
35
- useDebugValue ( displayName ) ;
36
- const [ data , setData ] = useState ( ( ) => ( {
37
- props,
38
- state : calculateState ( { } , props , options ) ,
39
- } ) ) ;
29
+ const useConnect =
30
+ ( options = { } ) =>
31
+ ( props ) => {
32
+ const {
33
+ calculateState,
34
+ shouldComponentUpdate,
35
+ displayName = "useConnect" ,
36
+ immutable,
37
+ } = options ;
38
+ useDebugValue ( displayName ) ;
39
+ const [ data , setData ] = useState ( ( ) => ( {
40
+ props,
41
+ state : calculateState ( { } , props , options ) ,
42
+ } ) ) ;
40
43
41
- const isMount = useMounted ( ) ;
44
+ const isMount = useMounted ( ) ;
42
45
43
- useEffect ( ( ) => {
44
- const { stores } = getStores ( { options, props } ) ;
45
- const storeLen = stores . length ;
46
- if ( storeLen ) {
47
- const handleChange = ( ) => {
48
- if ( T_FALSE !== isMount ( ) ) {
49
- setData ( ( prev ) =>
50
- handleShouldComponentUpdate ( {
51
- options,
52
- shouldComponentUpdate,
53
- calculateState,
54
- prev,
55
- props,
56
- } )
57
- ) ;
46
+ useEffect (
47
+ ( ) => {
48
+ const { allProps, firstStore } = getStores ( { options, props } ) ;
49
+ const handleChange = ( ) => {
50
+ if ( T_FALSE !== isMount ( ) ) {
51
+ setData ( ( prev ) =>
52
+ handleShouldComponentUpdate ( {
53
+ options,
54
+ shouldComponentUpdate,
55
+ calculateState,
56
+ prev,
57
+ props,
58
+ } )
59
+ ) ;
60
+ }
61
+ } ;
62
+ if ( ! data . __init__ || data . props !== props ) {
63
+ handleChange ( ) ;
58
64
}
59
- } ;
60
- if ( ! data . __init__ || data . props !== props ) {
61
- handleChange ( ) ;
62
- }
63
- const asyncHandleChange = ( ) => setImmediate ( handleChange ) ;
64
- for ( let i = 0 ; i < storeLen ; i ++ ) {
65
- stores [ i ] . addListener ( asyncHandleChange , CHANGE ) ;
66
- }
67
- return ( ) => {
68
- stores . forEach ( ( store ) =>
69
- store ?. removeListener ( asyncHandleChange , CHANGE )
70
- ) ;
71
- } ;
72
- }
73
- } , [ props ] ) ;
65
+ firstStore . addListener ( handleChange , CHANGE ) ;
66
+ return ( ) => {
67
+ firstStore . removeListener ( handleChange , CHANGE ) ;
68
+ } ;
69
+ } ,
70
+ immutable ? [ ] : [ props ]
71
+ ) ;
74
72
75
- return data . state || { } ;
76
- } ;
73
+ return data . state || { } ;
74
+ } ;
77
75
78
76
export default useConnect ;
0 commit comments