File tree Expand file tree Collapse file tree 4 files changed +28
-4
lines changed
Expand file tree Collapse file tree 4 files changed +28
-4
lines changed Original file line number Diff line number Diff line change @@ -18,6 +18,15 @@ const Demo = () => {
1818 < pre> {JSON .stringify (state, null , 2 )}< / pre>
1919 < button onClick= {() => setState ({hello: ' world' })}> hello< / button>
2020 < button onClick= {() => setState ({foo: ' bar' })}> foo< / button>
21+ < button
22+ onClick= {() => {
23+ setState ((prevState ) => ({
24+ count: prevState .count === undefined ? 0 : prevState .count + 1 ,
25+ }))
26+ }}
27+ >
28+ count
29+ < / button>
2130 < / div>
2231 );
2332};
Original file line number Diff line number Diff line change @@ -11,6 +11,15 @@ const Demo = () => {
1111 < pre > { JSON . stringify ( state , null , 2 ) } </ pre >
1212 < button onClick = { ( ) => setState ( { hello : 'world' } ) } > hello</ button >
1313 < button onClick = { ( ) => setState ( { foo : 'bar' } ) } > foo</ button >
14+ < button
15+ onClick = { ( ) => {
16+ setState ( ( prevState ) => ( {
17+ count : prevState . count === undefined ? 0 : prevState . count + 1 ,
18+ } ) )
19+ } }
20+ >
21+ count
22+ </ button >
1423 </ div >
1524 ) ;
1625} ;
Original file line number Diff line number Diff line change 11import * as React from 'react' ;
22
3- export type UseState = < T > ( initialState : T | ( ( ) => T ) ) => [ T , ( newState : T ) => void ] ;
3+ export type UseState = < T > ( initialState : T | ( ( ) => T ) ) => [ T , ( newState : T | ( ( newState ) => T ) ) => void ] ;
44export const useState : UseState = ( React as any ) . useState ;
55
66export type UseEffect = ( didUpdate : ( ) => ( ( ( ) => void ) | void ) , params ?: any [ ] ) => void ;
Original file line number Diff line number Diff line change 11import { useState } from './react' ;
22
3- const useSetState = < T extends object > ( initialState : T = { } as T ) : [ T , ( patch : Partial < T > ) => void ] => {
3+ const useSetState = < T extends object > ( initialState : T = { } as T ) : [ T , ( patch : Partial < T > | Function ) => void ] => {
44 const [ state , set ] = useState < T > ( initialState ) ;
55 const setState = ( patch ) => {
6- Object . assign ( state , patch ) ;
7- set ( state ) ;
6+ if ( patch instanceof Function ) {
7+ set ( ( prevState ) => {
8+ return Object . assign ( state , patch ( prevState ) )
9+ } )
10+ } else {
11+ Object . assign ( state , patch ) ;
12+ set ( state ) ;
13+ }
814 } ;
915
1016 return [ state , setState ] ;
You can’t perform that action at this time.
0 commit comments