atom(options)

atom 在 Rdx 中代表一个状态。atom() 函数返回一个可以读写的 RdxState。


function atom<T>({
id: string,
defaultValue: T | Promise<T> | RdxState<T>,
}): RdxState<T>
  • id 一个唯一的字符串,用来在 RdxContext 下标记一个唯一的 atom 状态。
  • defaultValue 当 atom 在 RdxContext 下初始化时的默认值。

通常的时候,atom 可以配合一下 hooks 一起使用


Example#

Root

The fallback content to display on prerendering
import React from 'react';
import { atom, useRdxState, RdxContext } from '@alife/rdx';
const Atom = atom({
id: 'atom',
defaultValue: 1,
});
export const Root = () => {
return (
<RdxContext>
<Counter />
</RdxContext>
);
};
const Counter = () => {
const [state, setState] = useRdxState(Atom);
return (
<div
style={{ display: 'flex', width: 100, justifyContent: 'space-around' }}
>
{/* 通过传递新的值来更新数据 */}
<button
onClick={() => {
setState(state + 1);
}}
>
+
</button>
<span>{state}</span>
{/* 通过传递updated function 来更新数据 */}
<button
onClick={() => {
setState((state) => {
return state - 1;
});
}}
>
-
</button>
</div>
);
};