# @dbeining/react-atom 中文文档

规范地址：https://npmcn.com/package/%40dbeining/react-atom/

版本：4\.1\.21
npm 元数据更新时间：2022-04-05T03:17:00.334Z
中文译文更新时间：2026-11-11T16:54:55.688Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40dbeining/react-atom
原文对照：https://npmcn.com/package/%40dbeining/react-atom/?lang=original
项目主页：https://derrickbeining.github.io/react-atom/
源码仓库：https://github.com/derrickbeining/react-atom

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：46.4 kB，10 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：react \>=16\.7\.0-alpha\.0 \|\| \>=16\.8\.0-alpha\.0 \|\| \>= 16\.8\.0 \< 17，react-dom \>=16\.7\.0-alpha\.0 \|\| \>=16\.8\.0-alpha\.0 \|\| \>= 16\.8\.0 \< 17
- 首次发布：2018-11-19T18:28:39.538Z
- 最新版本发布：2021-08-03T20:07:08.247Z
- 近 30 天下载量：24748（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：50（近 12 个月 0 个）

## 中文简介

国家管理使反应变得简单。 建于"反应钩"上. 灵感来自 `atom`单位 `reagent.cljs`。 。 。 .

## 安装

```sh
npm install @dbeining/react-atom
```

也可以使用：`pnpm add @dbeining/react-atom`、`yarn add @dbeining/react-atom`、`bun add @dbeining/react-atom`

## README

![react-atom logo](https://document-export.canva.com/DADKGVfSlSY/19/preview/0001-541240887.png)

### 管理共享状态的简单方法 [反应](https://reactjs.org/)

### 在反应上建造 [钩子 API](https://github.com/reactjs/reactjs.org/blob/f203cd5d86c4c611a31a4f72c5a91e2db0858ce3/content/docs/hooks-intro.md)

### 灵感来自 [原子](https://purelyfunctional.tv/guide/reagent/#atoms)单位 [试剂.cljs](https://reagent-project.github.io/)

[![TypeScript](https://badges.frapsoft.com/typescript/version/typescript-next.svg?v=101)](https://github.com/ellerbrock/typescript-badges/) [![npm (scoped)](https://img.shields.io/npm/v/@dbeining/react-atom.svg)](https://www.npmjs.com/package/@dbeining/react-atom) [![npm bundle size (minified)](https://img.shields.io/bundlephobia/min/@dbeining/react-atom.svg)](https://bundlephobia.com/result?p=@dbeining/react-atom) [![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/@dbeining/react-atom.svg)](https://bundlephobia.com/result?p=@dbeining/react-atom)

[![Build Status](https://travis-ci.com/derrickbeining/react-atom.svg?branch=master)](https://travis-ci.com/derrickbeining/react-atom) [![codecov](https://codecov.io/gh/derrickbeining/react-atom/branch/master/graph/badge.svg)](https://codecov.io/gh/derrickbeining/react-atom) [![npm](https://img.shields.io/npm/dt/@dbeining/react-atom.svg)](https://www.npmjs.com/package/@dbeining/react-atom)

[![NpmLicense](https://img.shields.io/npm/l/@dbeining/react-atom.svg)](https://www.npmjs.com/package/@dbeining/react-atom) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)

-   [说明](https://npmcn.com/package/%40dbeining/react-atom/#readme-description)
-   [为什么用 `react-atom`? 吗?](https://npmcn.com/package/%40dbeining/react-atom/#readme-why-use-react-atom)
-   [安装](https://npmcn.com/package/%40dbeining/react-atom/#readme-installation)
-   [文档](https://npmcn.com/package/%40dbeining/react-atom/#readme-documentation)
-   [代码示例 `react-atom` 行动](https://npmcn.com/package/%40dbeining/react-atom/#readme-code-example-react-atom-in-action)
-   [游戏 `react-atom` 在代码Sandbox中](https://npmcn.com/package/%40dbeining/react-atom/#readme-%F0%9F%95%B9%EF%B8%8F-play-with-react-atom-in-codesandbox-%F0%9F%8E%AE%EF%B8%8F)
-   [贡献/反馈](https://npmcn.com/package/%40dbeining/react-atom/#readme-contributing--feedback)

## 说明

`react-atom` 提供一种非常简单的方式来管理 React 中的状态, 对于全局应用程序状态和当地组件状态: QQ`Atom`s.

### 让你的状态 `Atom`数字 :

```ts
import { Atom } from "@dbeining/react-atom";

const appState = Atom.of({
  color: "blue",
  userId: 1
});
```

### 读取状态为 `deref`

你不能检查 `Atom` 你必须直接声明 `deref`像这样

```js
import { deref } from "@dbeining/react-atom";

const { color } = deref(appState);
```

### 更新状态 `swap`

你不能修改一个 `Atom` 直接说 更新状态的主要途径是: `swap`。这里是它的呼号:

```ts
function swap<S>(atom: Atom<S>, updateFn: (state: S) => S): void;
```

`updateFn` 适用于 `atom`'状态和返回值被设定为 `atom`新状态 只有两个简单的规则 `updateFn`数字 :

1.  它必须返回与上一个状态相同的类型/接口的值
2.  它不能改变 以前的状态

说明一下,我们如何更新 `appState`颜色 :

```js
import { swap } from "@dbeining/react-atom";

const setColor = color =>
  swap(appState, state => ({
    ...state,
    color: color
  }));
```

注意我们 `updateFn` 实值 [传播](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)将旧状态置入新对象后再压倒 `color`这很容易遵守 `updateFn`。 。 。 .

### 副作用吗? 刚刚使用 `swap`

你不需要做任何特别的 管理副作用。 照常写你的IO相关逻辑,然后打电话 `swap` 当你得到了你需要的。 例如:

```js
const saveColor = async color => {
  const { userId } = deref(appState);
  const theme = await post(`/api/user/${userId}/theme`, { color });
  swap(appState, state => ({ ...state, color: theme.color }));
};
```

### 在状态变化上与 QQ 重交组件`useAtom`QQ 自定义反应钩

`useAtom` 是一个 [自定义反应钩](https://github.com/reactjs/reactjs.org/blob/98c1d22fbef2638cafb03b07e0eabe2a6186fca8/content/docs/hooks-custom.md)它做两件事:

1.  返回原子的当前状态(如 `deref`),以及
2.  将您的组件订阅到原子上, 这样它每次状态变化时都会重递

看起来是这样的:

```js
export function ColorReporter(props) {
  const { color, userId } = useAtom(appState);

  return (
    <div>
      <p>
        User {userId} has selected {color}
      </p>
      {/* `useAtom` hook will trigger a re-render on `swap` */}
      <button onClick={() => swap(appState, setRandomColor)}>Change Color</button>
    </div>
  );
}
```

> Nota Bene:您也可以使用选择器通过使用 `options.select` 参数. [读取文件](https://derrickbeining.github.io/react-atom/globals.html#useatom) 详细情况.

## 为什么用 `react-atom`? 吗?

😌 **微小 API / 学习曲线**

> \`Atom.of'、\`使用Atom'和\`swap'将涵盖绝大多数的使用案例.

🚫 **没有锅炉板,只有可预测的状态管理**

> 减速器? 行动? 汤克斯? 萨加斯? 不,只是"扫荡(原子,新国家)".

🎵 **表演部件渲染训练**

> 这个 `useAtom` 钩子接受可选 `select` 函数让组件订阅计算状态。 这意味着该组件只有在返回的值从 `select` 变化.

😬 **`React.useState` 玩不开心 `React.memo`**

> `useState` 很酷,直到你意识到,在大多数情况下,它迫使你通过每个渲染处的道具传递新的函数实例,因为你通常需要包接 `setState` 函数。 这很难利用 `React.memo`。例如:
> 
> \-- -- . .
> 
> ```jsx
> function Awkwardddd(props) {
>   const [name, setName] = useState("");
>   const [bigState, setBigState] = useState({ ...useYourImagination });
> 
>   const updateName = evt => setName(evt.target.value);
>   const handleDidComplete = val => setBigState({ ...bigState, inner: val });
> 
>   return (
>     <>
>       <input type="text" value={name} onChange={updateName} />
>       <ExpensiveButMemoized data={bigState} onComplete={handleDidComplete} />
>     </>
>   );
> }
> ```
> 
> 每一次 `input` 火灾 `onChange`, (中文(简体) ), `ExpensiveButMemoized` 必须重新投降,因为 `handleDidComplete` 与最后通过的判决不完全相同.
> 
> 反应文件承认这很尴尬 [建议利用背景来研究](https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down),因为 [替代品是超曲折的](https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback)。 。 。 .
> 
> 与 `react-atom`这个问题根本不存在 您可以在组件外定义您的更新功能, 以便它们具有优异的稳定性 .
> 
> ```jsx
> const state = Atom.of({ name, bigState: { ...useYourImagination } });
> 
> const updateName = ({ target }) => swap(state, prev => ({ ...prev, name: target.value }));
> 
> const handleDidComplete = val =>
>   swap(state, prev => ({
>     ...prev,
>     bigState: { ...prev.bigState, inner: val }
>   }));
> 
> function SoSmoooooth(props) {
>   const { name, bigState } = useAtom(state);
> 
>   return (
>     <>
>       <input type="text" value={name} onChange={updateName} />
>       <ExpensiveButMemoized data={bigState} onComplete={handleDidComplete} />
>     </>
>   );
> }
> ```
TS 翻译 **第一等类型脚本支持**

> `react-atom` 以 TypeScript 写成,这样每个版本都会以正确,高质量的打字方式发布.

👣 **小脚印**

>  [![react-atom minified file size](https://img.shields.io/bundlephobia/min/@dbeining/react-atom.svg)](https://bundlephobia.com/result?p=@dbeining/react-atom)[![react-atom minified+gzipped file size](https://img.shields.io/bundlephobia/minzip/@dbeining/react-atom.svg)](https://bundlephobia.com/result?p=@dbeining/react-atom) ⚛️ **拥抱与虎克的未来**

> 虎克会做的 `class` 部件及其种类(更高级部件、成品相干部件和随子功能相干部件)已过时. `react-atom` 使得管理共享状态变得容易,只有函数组件和钩子.

## 安装

```
npm i -S @dbeining/react-atom
```

## 依赖关系

`react-atom` 有一个捆绑的依赖, [@libre/原子语](https://github.com/libre-org/atom),它提供了原子数据类型。 其全部再出口自 `@dbeining/atom`文档 [这里](https://libre-org.github.io/atom/)。 。 。 .

`react-atom` 也有两个 `peerDependencies`,即:, `react@^16.8.0` 财务报告和审定财务报表 `react-dom@^16.8.0`包含Hooks API.

## 文档

[`react-atom` API 密码](https://derrickbeining.github.io/react-atom/)

[`@libre/atom` API 密码](https://libre-org.github.io/atom/)

## 代码示例 `react-atom` 行动

点击代码样本

```jsx
import React from "react";
import ReactDOM from "react-dom";
import { Atom, useAtom, swap } from "@dbeining/react-atom";

//------------------------ APP STATE ------------------------------//

const stateAtom = Atom.of({
  count: 0,
  text: "",
  data: {
    // ...just imagine
  }
});

//------------------------ EFFECTS ------------------------------//

const increment = () =>
  swap(stateAtom, state => ({
    ...state,
    count: state.count + 1
  }));

const decrement = () =>
  swap(stateAtom, state => ({
    ...state,
    count: state.count - 1
  }));

const updateText = evt =>
  swap(stateAtom, state => ({
    ...state,
    text: evt.target.value
  }));

const loadSomething = () =>
  fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then(res => res.json())
    .then(data => swap(stateAtom, state => ({ ...state, data })))
    .catch(console.error);

//------------------------ COMPONENT ------------------------------//

export const App = () => {
  const { count, data, text } = useAtom(stateAtom);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Text: {text}</p>

      <button onClick={increment}>Moar</button>
      <button onClick={decrement}>Less</button>
      <button onClick={loadSomething}>Load Data</button>
      <input type="text" onChange={updateText} value={text} />

      <p>{JSON.stringify(data, null, "  ")}</p>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
```

## 游戏 `react-atom` 在代码Sandbox中

你可以玩游戏 `react-atom` 立即在下列链接中没有设置 :

| Java 脚本沙盒 | 类型脚本沙盒 |
| --- | --- |
| [![try react-atom](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/m3x9wn6kmy) | [![try react-atom](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/km72yynqov) |

## 贡献/反馈

如果您有任何问题和建议,请开始讨论 改进/特性,或想要提交错误修正的PR(请包括 (如果适用的话).

## 常见问题

### @dbeining/react-atom 是什么？

国家管理使反应变得简单。 建于"反应钩"上\. 灵感来自 atom单位 reagent\.cljs。 。 。 \.

### 如何安装 @dbeining/react-atom？

在项目目录运行 npm install @dbeining/react-atom，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（\>=16\.7\.0-alpha\.0 \|\| \>=16\.8\.0-alpha\.0 \|\| \>= 16\.8\.0 \< 17）、react-dom（\>=16\.7\.0-alpha\.0 \|\| \>=16\.8\.0-alpha\.0 \|\| \>= 16\.8\.0 \< 17）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @dbeining/react-atom 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @dbeining/react-atom 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @dbeining/react-atom 可以商用吗？

@dbeining/react-atom 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @dbeining/react-atom 的下载量有多少？

根据 npm 官方下载统计，@dbeining/react-atom 在 2026/10/12 – 2026/11/10 这 30 天内被下载 24,748 次，日均约 825 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @dbeining/react-atom 还在维护吗？

最新版本 4\.1\.21 发布于 2021/08/04（5 年前）；至今共发布 50 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/11/20。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

