|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + makeImmutable, |
| 4 | + responseImmutable, |
| 5 | + useContext, |
| 6 | +} from '@rc-component/context'; |
| 7 | +import React from 'react'; |
| 8 | +import useRenderTimes from './useRenderTimes'; |
| 9 | + |
| 10 | +const AppContext = createContext<{ |
| 11 | + appCnt: number; |
| 12 | + appUpdateCnt: number; |
| 13 | +}>(); |
| 14 | + |
| 15 | +const MyApp = ({ rootCnt, children }: { rootCnt: number; children?: React.ReactNode }) => { |
| 16 | + const [appCnt, setAppCnt] = React.useState(0); |
| 17 | + const [appUpdateCnt, setAppUpdateCnt] = React.useState(0); |
| 18 | + const renderTimes = useRenderTimes(); |
| 19 | + |
| 20 | + return ( |
| 21 | + <AppContext.Provider value={{ appCnt, appUpdateCnt }}> |
| 22 | + <button type="button" onClick={() => setAppCnt(v => v + 1)}> |
| 23 | + App CNT: {appCnt} |
| 24 | + </button> |
| 25 | + <button type="button" onClick={() => setAppUpdateCnt(v => v + 1)}> |
| 26 | + App Need Component Update CNT: {appUpdateCnt} |
| 27 | + </button> |
| 28 | + App Render Times: {renderTimes} / Root CNT: {rootCnt} |
| 29 | + <div style={{ border: '1px solid blue', padding: 16 }}>{children}</div> |
| 30 | + </AppContext.Provider> |
| 31 | + ); |
| 32 | +}; |
| 33 | +const ImmutableMyApp = makeImmutable(MyApp); |
| 34 | + |
| 35 | +const MyComponent = ({ name }: { name: any }) => { |
| 36 | + const renderTimes = useRenderTimes(); |
| 37 | + const value = useContext(AppContext, name); |
| 38 | + |
| 39 | + return ( |
| 40 | + <div> |
| 41 | + {name}: {value} / Component Render Times: {renderTimes} |
| 42 | + </div> |
| 43 | + ); |
| 44 | +}; |
| 45 | +const ImmutableMyComponent = responseImmutable(MyComponent); |
| 46 | + |
| 47 | +export default () => { |
| 48 | + const [rootCnt, setRootCnt] = React.useState(0); |
| 49 | + const renderTimes = useRenderTimes(); |
| 50 | + |
| 51 | + return ( |
| 52 | + <> |
| 53 | + {' '} |
| 54 | + <button type="button" onClick={() => setRootCnt(v => v + 1)}> |
| 55 | + Root CNT: {rootCnt} |
| 56 | + </button> |
| 57 | + Root RenderTimes: {renderTimes}{' '} |
| 58 | + <div style={{ border: '1px solid red', padding: 16 }}> |
| 59 | + <ImmutableMyApp rootCnt={rootCnt}> |
| 60 | + <ImmutableMyComponent name="appUpdateCnt" /> |
| 61 | + <ImmutableMyComponent name="notConsumeAppContext" /> |
| 62 | + </ImmutableMyApp> |
| 63 | + </div> |
| 64 | + </> |
| 65 | + ); |
| 66 | +}; |
0 commit comments