【发布时间】:2021-07-10 16:08:34
【问题描述】:
我只是在学习 React JS。我想在我的应用程序中获取一个以 mobx 状态存储的值。但不知道如何在功能组件中获取 mobx 状态。
const user_id = observer(({ GlobalStore }) =>
console.log(GlobalStore.user_id)
); // I just need the user ID.
这是完整的代码:
import { observer } from "mobx-react";
import Store from "../mobx/Store";
export const user_id = observer(({ GlobalStore }) =>
console.log(GlobalStore)
);
console.log(user_id);
我的 Store.js 文件如下:
import { observable, action, makeObservable, autorun } from "mobx";
class GlobalStore {
site_title = "ABCD";
app_code = null;
user_id = null;
constructor() {
makeObservable(this, {
site_title: observable,
app_code: observable,
user_id: observable,
update_title: action.bound,
update_appcode: action.bound,
update_userid: action.bound,
});
}
update_title(title) {
this.site_title = title;
}
update_appcode(code) {
this.app_code = code;
}
update_userid(id) {
this.user_id = id;
}
}
const Store = new GlobalStore();
autorun(() => {
console.log("System Checking... OK")
})
export default Store;
【问题讨论】:
-
我不太明白你到底想要什么?你只是想从你的 Store in React 组件中渲染一些值吗?不清楚,因为您的示例中没有组件,
user_id只是一个记录事物的函数,它甚至没有任何 jsx。 -
@Danila 我只想在不同的功能组件或模块中将 mobx 状态 (user_id) 设为
user_id = Get mobx state here anyhow
标签: javascript reactjs react-hooks mobx mobx-react