YuJian920
2 years ago
2 changed files with 9 additions and 5 deletions
@ -1,6 +1,10 @@
@@ -1,6 +1,10 @@
|
||||
{ |
||||
"nodes":[ |
||||
{"id":"70300943eedb4f0d","x":-724,"y":-538,"width":813,"height":426,"type":"text","text":"从 zustand/react.ts 文件开始,先看看 create 函数的代码实现。\n```tsx\nexport const create = (<T>(createState: StateCreator<T, [], []> | undefined) => {\n\t// creare 函数的核心是 createImpl 函数\n\tcreateState ? createImpl(createState) : createImpl) as Create\n}\n```"} |
||||
{"id":"70300943eedb4f0d","x":-903,"y":-556,"width":742,"height":182,"type":"text","text":"从 zustand/react.ts 文件开始,先看看 create 函数的代码实现。\n```tsx\nexport const create = (<T>(createState: StateCreator<T, [], []> | undefined) => {\n\t// creare 函数的核心是 createImpl 函数\n\tcreateState ? createImpl(createState) : createImpl) as Create\n}\n```"}, |
||||
{"id":"8a1c4d4e899e9dad","x":-903,"y":-290,"width":974,"height":361,"type":"text","text":"从 createImpl 函数的代码中可以看到,调用了 Object.assign() 函数合并 useBoundStore 和 api 对象,这也是为什么,通过 create 创建返回的 Hook 可以在没有 React 的环境通过访问内部属性的方式执行。\n```tsx\nconst createImpl = <T>(createState: StateCreator<T, [], []>) => {\n\t// 判断 createState 是否函数,是则执行 createStore 函数, 否则直接赋值为 createState\n\tconst api = typeof createState === \"function\" ? createStore(createState) : createState;\n\tconst useBoundStore: any = (selector?: any, equalityFn?: any) => useStore(api, selector, equalityFn);\n\t// 合并 api 到 useBoundStore,实际上就是合并到 useStore 执行之后的返回值,因为函数也是对象\n\tObject.assign(useBoundStore, api);\n\t// 最后将 useBoundStore 返回,完成 store 创建\n\treturn useBoundStore;\n};\n```\ncreateImpl 函数中用到了了两个函数,分别是 createStore 和 useStore"}, |
||||
{"id":"1c7f002a32cbff2b","x":-934,"y":210,"width":665,"height":464,"type":"text","text":"```tsx\nexport function useStore<TState, StateSlice>(\n api: WithReact<StoreApi<TState>>,\n selector: (state: TState) => StateSlice = api.getState as any,\n equalityFn?: (a: StateSlice, b: StateSlice) => boolean\n) {\n\t// 自定义一个基于 useSyncExternalStoreWithSelector 的 Hook 并返回\n const slice = useSyncExternalStoreWithSelector(\n api.subscribe,\n api.getState,\n api.getServerState || api.getState,\n selector,\n equalityFn\n );\n useDebugValue(slice);\n return slice;\n}\n```"} |
||||
], |
||||
"edges":[] |
||||
"edges":[ |
||||
{"id":"1b4e70ab90f0b813","fromNode":"70300943eedb4f0d","fromSide":"bottom","toNode":"8a1c4d4e899e9dad","toSide":"top"} |
||||
] |
||||
} |
Loading…
Reference in new issue