首页 > 解决方案 > 当其他 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>)
})

标签: reactjsmobx

解决方案


我只注意到一件事。你忘了用observer.

//   --------------  IMPORTANT! ----------------
const DoSomething = observer(() => {...})

这是一个代码框来说明:

编辑 hardcore-hooks-4cdrp


推荐阅读