💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## useSyncExternalStore 1. 如果你需要去集成已有的非 React 代码,`useSyncExternalStore` API 是很有用的。 2. 调用向使用浏览器的API ## 示例 sub.ts ``` import { useSyncExternalStore } from 'react'; import { counterStore } from '../lib/sub'; function Counter() { const count = useSyncExternalStore( counterStore.subscribe, counterStore.getSnapshot, counterStore.getServerSnapshot ); return ( <div> <p>计数: {count}</p> <button onClick={() => counterStore.setValue(count + 1)}> 增加 </button> </div> ); } export default Counter; ``` demo.txs ``` import { useSyncExternalStore } from 'react'; import { counterStore } from '../lib/sub'; function Counter() { const count = useSyncExternalStore( counterStore.subscribe, counterStore.getSnapshot, counterStore.getServerSnapshot ); return ( <div> <p>计数: {count}</p> <button onClick={() => counterStore.setValue(count + 1)}> 增加 </button> </div> ); } export default Counter; ``` 通常可以把useSyncExternalStore 封装到 hook 中 如 ``` import { counterStore } from "@/lib/sub"; import { useSyncExternalStore } from "react"; export const useCount = () => { const count = useSyncExternalStore( counterStore.subscribe, counterStore.getSnapshot, counterStore.getServerSnapshot ); return count } ``` 调用 ``` // 子组件 function Counter() { const count = useCount() return ( <div> <p>计数: {count}</p> </div> ); } // 调用 export default function Demo(){ const count = useCount() return <div> <Counter /> <Counter /> <button onClick={() => counterStore.setValue(count + 1)}>button</button> </div> } ```