快速开始

在开始页面中一次性查看核心内容和实际运行的示例。


1. 安装

分割/拖动hooks使用 React hook 和 RxJS BehaviorSubject因此应用程序需要 react, rxjs一起使用。

bash
npm install @byeolnaerim/global-rx-state rxjs react

2. 共享相同名称的 store

命名模式旨在方便在组件内部调用。通过相同名称调用将返回相同的全局 store。如果下一个值依赖于上一个值, createRxState请使用形式的功能设置器。 setValue((prev) => next) 3. 如果需要运行时键,请使用 createRxStateTuple

tsx
import { createRxState } from "@byeolnaerim/global-rx-state";

function CounterButtons() {
  const { setCountInner, useCountInner } = createRxState(
    0,
    "countInner",
    { storage: "localstorage" },
  );

  const countInner = useCountInner();

  return (
    <button onClick={() => setCountInner((prev) => prev + 1)}>
      {countInner}
    </button>
  );
}

function CounterDisplay() {
  const { useCountInner } = createRxState(0, "countInner", { storage: "localstorage" });
  const countInner = useCountInner();

  return <span>현재 count: {countInner}</span>;
}

当名称在运行时确定,例如从服务器接收的工作区 ID、路由参数或用户点击的选项卡名称时,

这是自然的。以下示例为每个选项卡使用不同的草稿 store。 createRxStateTuple4. 如果有更改规则,请通过 reducer 聚合

tsx
import { createRxStateTuple } from "@byeolnaerim/global-rx-state";

function RuntimeTabDraftSample() {
	const [setActiveTab, , useActiveTab] = createRxStateTuple(
		"profile",
		"docsQuickActiveTab",
		{ storage: "sessionstorage" },
	);
	const activeTab = useActiveTab();
	const [setDraft, , useDraft] = createRxStateTuple(
		{ content: "" },
		`docsQuickDraft:${activeTab}`,
		{ storage: "sessionstorage" },
	);
	const draft = useDraft();

	return (
		<Paper variant="outlined" sx={{ p: 2, borderRadius: 3 }}>
			<Stack spacing={1.5}>
				<Stack direction="row" spacing={1}>
					{["profile", "settings", "billing"].map((tabName) => (
						<Button
							key={tabName}
							variant={
								activeTab === tabName ? "contained" : "outlined"
							}
							onClick={() => setActiveTab(tabName)}
						>
							{tabName}
						</Button>
					))}
				</Stack>
				<TextField
					label={`${activeTab} draft`}
					value={draft.content}
					onChange={(event) =>
						setDraft({ content: event.target.value })
					}
					fullWidth
				/>
			</Stack>
		</Paper>
	);
}

简单值使用设置器就足够了,但如果状态根据多个操作而变化或值相互依赖,

将更改规则集中在一个地方是更安全的。 createRxReducerA 组件

tsx
type TodoAction =
  | { type: "add"; text: string }
  | { type: "reset" };

function todoReducer(state: TodoState, action: TodoAction): TodoState {
  switch (action.type) {
    case "add":
      return { items: [...state.items, action.text] };
    case "reset":
      return { items: [] };
    default:
      return state;
  }
}

const { dispatchTodo, useTodo } = createRxReducer(
  { items: [] },
  todoReducer,
  "todo",
);
© 2026 Byeolnaerim. 保留所有权利.介绍隐私政策