如何使用嵌套mobx存储的react上下文



我有两个存储:formStoreprofileStore

FormStore

export class ProfileFormStore {
@observable editing = false;
profileStore = new ProfileStore(this.roleId);
originalValue?: ApiModel | null;
@action.bound
startEdit() {
// this.originalValue = this.profileStore.toJson();  
/*  if uncomment above, next error thrown
RangeError: Maximum call stack size exceeded
at initializeInstance (mobx.module.js:391)
at ProfileStore.get (mobx.module.js:381)
at ProfileStore.get
*/
this.editing = true;
}
}

ProfileStore

export class ProfileStore {
@observable userProfile: ApiModel = {
userProfile: {
newsAndUpdates: false,
email: "",
phone: "",
lastName: "",
firstName: "",
},
};
@observable email = "";
@action.bound
fetch() {
// this.fromJson(this.actions.fetch());
console.log("start");
this.email = "qwe";
console.log("end");
}
@computed
toJson(): ApiModel {
return {
userProfile: {
firstName: this.userProfile.userProfile.firstName,
lastName: this.userProfile.userProfile.lastName,
phone: this.userProfile.userProfile.phone,
email: this.userProfile.userProfile.email,
newsAndUpdates: this.userProfile.userProfile.newsAndUpdates,
},
};
}
}

我想使用上下文

const formStore = new ProfileFormStore();
export const profileFormContext = React.createContext({
formStore,
profileStore: formStore.profileStore,
});
export const useProfileContext = () => React.useContext(profileFormContext);

并且有两个组件:formformControl

const controls = {
admin: (<><ProfileName /><Email /></>),
user: (<><ProfileName /></>)
};
export const Form = () => {
const { formStore, profileStore } = useProfileContext();
// this.fromJson(this.actions.fetch()); // if uncomment throws 'Missing option for computed get'
return <form>(controls.admin)</form>
}
export const ProfileName = () => {
const { formStore, profileStore } = useProfileContext();
formStore.startEdit(); // check form store, when assigning from profileStore get overflow error
return formStore.editing ? <input value='test' /> : <label>Test</label>
}

所以有两种错误:

  1. 从属于FormStoreProfileStore访问observables
  2. 在作为FormStore一部分的ProfileStore中更新observables

FormStore工作良好的

通过React.useContext注入的两个存储都遵循了以下示例https://mobx-react.js.org/recipes-context,但是它们的存储没有嵌套。我让它们嵌套,因为我想从formStore访问profileStore

这些错误是什么意思?如何修复它们?

实际上这不是答案:(但我使用的解决方案是

export class ProfileStore {
@observable editing;
@observablt userProfile: UserProfile;
...
}

仅此而已,我很高兴这个解决方案正在发挥作用,而不是使用两个商店,现在有一个商店。我想那个错误是我忘记在toJson处写入get。如果将来我遇到同样的错误并理解为什么会发生。我会尽量不要忘记更新这个答案。

相关内容

  • 没有找到相关文章

最新更新