想要展示如何在 React 组件之间共享任何可序列化的数据,例如NextJS 中的客户端组件。
我们有一些不相关的组件:
让我们创建一个包含初始状态的对象
export const state: { count: number } = { count: 0 };
我们可以将数据存储在 Map 或 WeakMap 中,状态将是访问它的键。另外,还需要一个订阅者数组。
const stateMap = new WeakMap
现在让我们编写一个钩子来订阅数据更改。
export function useCommonState(stateObj: T) { // more efficient than `useEffect` since we don't have any deps React.useInsertionEffect(() => { const cb = () => { const val = stateMap.get(stateObj); _setState(val!); }; // subscribe to events subscribers.push(cb); return () => { subscribers.slice(subscribers.indexOf(cb), 1); }; }, []); }
现在让我们添加与获取和设置状态相关的逻辑
// all instances of hook will point to same object reference const [state, _setState] = React.useState(() => { const val = stateMap.get(stateObj) as T; if (!val) { stateMap.set(stateObj, stateObj) return stateObj } return val }); const setState = React.useCallback((newVal: object) => { // update value stateMap.set(stateObj, newVal); // notify all other hook instances subscribers.forEach((sub) => sub()); }, []); return { state, setState };
现在可以在 3 个组件中使用它,例如
import { state as myState } from './state'; //... const { state, setState } = useCommonState(myState); // ... Component ACount: {state.count}
您可以在这里查看它是如何工作的 https://stackblitz.com/~/github.com/asmyshlyaev177/react-common-state-example
或者在这里https://codesandbox.io/p/github/asmyshlyaev177/react-common-state-example/main
或者在github https://github.com/asmyshlyaev177/react-common-state-example
根据这个原则查看我的 NextJS 库 https://github.com/asmyshlyaev177/state-in-url
Tnx 供阅读。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3