其他React组件访问商店时Mobx状态丢失

时间:2020-04-18 23:10:04

标签: reactjs 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>)
})

1 个答案:

答案 0 :(得分:0)

我刚刚注意到一件事。您忘记了用observer装饰组件。

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

下面是一个代码框来说明:

Edit hardcore-hooks-4cdrp