MobX - 用户配置文件不同的字段和空默认值问题

MobX - User profile different fields and null defaults issue

我有一个具有这些 userData 默认值的 AuthStore:

@observable userData = {
   username:  null,
   firstname: null,
   lastname:  null,
   email:     null
}

该对象在登录时填充了相应的字段,如下所示:

@observable userData = {
    username:  "jdoe",
    firstname: "john",
    lastname:  "doe",
    email:     "johndoe@website.com" <— This field is special
}

电子邮件字段很特殊,只有当经过身份验证的用户查看自己的个人资料时,它才应该是 fetched/existent。当访问另一个用户的个人资料时,除了电子邮件之外的所有其他字段都应该存在,并且是从没有电子邮件的 api 中获取的。

因为这是 2 种不同类型的用户,一个身份验证用户有他们的电子邮件,当他们访问任何其他用户时,没有电子邮件,只有所有其他相应的字段。处理此多用户数据用例的最佳方法是什么?

  1. 是否应该有 2 家商店除了电子邮件之外具有相同的重复字段?因此,上面的电子邮件在 AuthStore 中完好无损,然后是另一个具有相同字段但没有电子邮件的 UserStore,并创建了 2 个不同的 React Native ownerProfile.js(对于 auth 用户)和 profile.js(对于其他用户) ?这感觉不对...

  2. 如果可用,存储登录的 userData 对象以便在应用程序刷新时检索它的最佳方法是什么,因为它目前在应用程序刷新时清空配置文件的 userData 字段,访问配置文件会导致错误,因为我使用 AuthStore.userData.username.toUpperCase();我得到一个错误,因为它试图 运行 .toUpperCase() on null.

我遇到了 hydrate/toJson,但我对整个事情感到困惑,甚至不确定 when/how 实施它们,或者即使它们是我问题的解决方案。由于这个问题,我卡在了我的项目中,无法继续前进。

知道如何使用 MobX 解决这个问题吗?

我会创建一个 class User

class User {
  @observable username = null;
  @observable firstname = null;
  @observable lastname = null;
  @observable email = null;
}

然后你可以创建 UserStore,其中包含 User 个实例的可观察数组,AuthStore 具有指向当前用户配置文件的可观察字段 self

create 2 different react native ownerProfile.js (for auth user) and profile.js (for other users)? This doesn’t feel right...

我通常会重用现有组件,但如果我开始向组件添加太多 if,我认为这是将代码提取到单独组件中的明确信号。

很难说什么时候应该拆分 OwnerProfileProfile,这取决于你想在那里显示什么。请记住,您可以这样做

function UserProfile({ user, otherProps }) {
  return (
   <common>
    <markup>
     <goes here>
     { user.email 
       ? <OwnerProfile user={user} {...otherProps} />
       : <Profile user={user} {...otherProps} />
     </goes here>
    </markup>
   </common>
  );
}

如果您需要用相同的标记包装 OwnerProfileProfile(或者您可以将 UserProfile 变成 HOC 并将其应用于 ProfileOwnerProfile 出口)。

What’s the best way to store the logged in userData object to retrieve it on application refresh if it’s available

你可以看看mobx-contact-list example. Here it loads contacts from localStorage and here它保存到localStorage。