reactjs - 当其他 React 组件访问存储时 Mobx 状态丢失
问题描述
我正在尝试学习如何将 mobx 与 React Hooks 一起使用。但我不明白为什么当一个组件加载存储数据(使用 loadData())时,我能够从存储中观察到更新的值,但是当另一个组件访问存储数据时,存储数据中的所有内容都会重置回其默认值。我在这里想念什么?
我的开发平台使用的是 Nodejs v12.16.1
我的 React 依赖项是:
“mobx”:“^5.15.4”,“mobx-react-lite”:“^1.5.2”,“react”:“^16.13.1”,
import { createContext } from 'react';
import { observable, action, decorate, flow } from "mobx";
import agent from '../api/agent';
import { history } from "../index";
class ApplicationStore {
user = {
profile: { id: null, firstName: null, lastName: null, email: null, phoneNumber: null }
};
loading = false;
loadData = flow(function *() {
this.loading = true;
try {
const payload = yield agent.User.get('defaultUser');
this.user.profile.id = payload.user.profile.id;
this.user.profile.firstName = payload.user.profile.firstName;
this.user.profile.lastName = payload.user.profile.lastName;
this.user.profile.email = payload.user.profile.email;
this.user.profile.phoneNumber = payload.user.profile.phoneNumber;
} catch (err) {
console.log(err);
history.push('/systemDown');
} finally {
this.loading = false;
}
});
}
decorate(ApplicationStore, {
user: observable,
loading: observable,
//loadData: action, //Defining as an action or not makes no difference
})
export default createContext(new ApplicationStore()); //NOTE: Creating context here.
const HomePage = observer(() => {
const applicationStore = useContext(ApplicationStore);
useEffect(() => {
applicationStore.loadData();
}, [applicationStore]);
if (applicationStore.loading)
return <LoadingComponent content="Loading data..." />;
return (<DoSomething/>)
})
const DoSomething = observer(() => {
const applicationStore = useContext(ApplicationStore);
return (<div>
// ERROR: applicationStore.user.profile is back to its default values. Why???
</div>)
})
解决方案
推荐阅读
- javascript - 如何在 undici 中使用经过身份验证的代理
- reporting-services - SSRS - 执行布尔 IFF 表达式时忽略 NULL
- java - 如何正确转换opencsv中的字段?
- bash - hiera(Puppet)yaml中的cronjob在一行中的几个命令
- python - 允许机器人命令(仅用于测试)
- javascript - TypeScript 遍历对象并从值创建类型
- flutter - 如何在 Flutter 中有一个嵌套的 SliverList?
- apache-spark - 在 pyspark 中执行大规模可并行化的任务
- excel - 如何按功能选择单元格
- nuxt.js - vue 路由操作。(#)