React コンポーネント間でシリアル化可能なデータを共有する方法を示したいと考えています。 NextJS のクライアント コンポーネント。
無関係なコンポーネントがいくつかあります:
初期状態を含むオブジェクトを作成しましょう
export const state: { count: number } = { count: 0 };
データを Map または WeakMap に保存できます。状態はそれにアクセスするためのキーになります。また、subscribers 配列も必要になります。
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
読み取り用に送信します。
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3