# 编写raexel

### reaxel的结构

之前章节已经介绍过了reaxel是S（state状态）A（action行为）L（logic逻辑）L（lifecycle生命周期）的封装 -- 但这些的任意一种都不是组成reaxel的必要条件。通俗地说：reaxel内部可以不集成SALL中的任何一个或多个，这完全取决于你如何使用它！

```tsx
// Some code
export const 
```

假设我们需要一个用户SALL以管理用户的登录态和登录信息。

reaxes架构推荐使用以下方式组织你SALL :&#x20;

```tsx
// reaxel--user.tsx
import { orzMobx, Reaxlass, Reaxper, collectDeps, Reaxes } from "reaxes";

export const reaxel__user = (function () {
  const { store, setState } = orzMobx({
    userInfo: null,
    pending: false
  });

  return () => {
    return {
      get userInfo() {
        return store.userInfo;
      },
      get pending() {
        return store.pending;
      },
      fetchUserInfo() {
        setState({ pending: true });
        const result = fetchUserInfo();
        result.then((info) =>
          setState({
            userInfo: info,
            pending: false
          })
        );
        return result;
      },
      logout() {
        setState({ userInfo: null });
      }
    };
  };
})();

const fetchUserInfo = () =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: "路人甲",
        age: 23
      });
    }, 2500);
  });

```

reaxel将在你的React应用运行的那一刻被部署, 所有reaxel都会在react渲染视图之前自动执行完毕。

```tsx
// User.tsx
import { Reaxlass, Reaxper, orzMobx, Reaxes } from "reaxes";

import { reaxel__user } from "./reaxel--user";

export const User = Reaxper((props) => {
  const { userInfo, pending } = reaxel__user();

  return (
    <>
      {pending && <Loading />}
      {userInfo ? <UserInfo /> : <Empty />}
    </>
  );
});

const Empty = Reaxper(() => {
  const { pending, fetchUserInfo } = reaxel__user();
  if (pending) return null;
  return (
    <div>
      当前用户没登陆~
      <p>
        <button onClick={() => fetchUserInfo()}>登陆</button>
      </p>
    </div>
  );
});

const Loading = Reaxper(() => {
  return <p>正在请求用户信息,请稍候</p>;
});

const UserInfo = Reaxper(() => {
  const { userInfo, logout } = reaxel__user();

  return (
    <div>
      <p>用户已登陆</p>
      <p>用户名: {userInfo.name}</p>
      <p>年龄: {userInfo.age}</p>
      <button
        onClick={() => {
          logout();
        }}
      >
        注销
      </button>
    </div>
  );
});
```

{% embed url="https://codesandbox.io/embed/dreamy-haze-ihucun?fontsize=14&hidenavigation=1&theme=light" %}

完整示例：[CodeSandbox](https://codesandbox.io/embed/dreamy-haze-ihucun?fontsize=14\&hidenavigation=1\&theme=light)
