简体   繁体   English

React-native MobX @observable始终未定义

[英]React-native MobX @observable is always undefined

globalStore.js

import {observable} from 'mobx';

export default class globalStore {
    @observable loggedIn = false;
}

Followed by main App.js : 其次是主要App.js

import LoginForm from './src/components/LoginForm';
import { observer } from 'mobx-react';
import globalStore from './src/store/globalStore';

which renders loginForm: 呈现loginForm:

      return (
            <LoginForm store={globalStore} />
      );

In LoginForm , I wish to access the "loggedIn" observable: LoginForm ,我希望访问可观察到的“ loggedIn”:

observer 观察者

class LoginForm extends Component { / ... 

render() {
        console.log(this.props.store.loggedIn); 

Result: undefined 结果: undefined

Desired result: false 所需结果: false

Why does this not work? 为什么这不起作用?

Do I need a Provider wrapping the LoginForm component? 我是否需要提供程序来包装LoginForm组件? How come? 怎么会?

Wrapping my entire in the App.js in a Provider with the store does not work either 在商店的Provider App.js我的全部包裹在App.js中也不起作用

I cannot see the instance of your global store class 我看不到您的全局商店类的实例

try 尝试

import {observable} from 'mobx';

class globalStore {
    @observable loggedIn = false;
}
const global_store=new globalStore(); // as a singleton class
export default global_store;

then your login form will be like below 那么您的登录表单将如下所示

 return (
            <LoginForm store={global_store} />
      );

or may be you can instantiate it on your login form as well 或者也可以在您的登录表单上实例化它

I think there are few things from my point of view I've doing differently with a working implementation: 从我的角度来看,我认为对于有效的实现我所做的事情有所不同:

First you need to create new store from your GlobalStore . 首先,您需要从GlobalStore创建新商店。 I've done it this way: 我这样做是这样的:

class GlobalStore {
  @observable loggedin = false;
  ...
}

const store = new GlobalStore();
export default store;

Then you should use provider: 然后,您应该使用提供程序:

import GlobalStore from './path/to/stores/GlobalStore';

<Provider
  globalStore={GlobalStore}
>
  <AppRelatedContainers />
</Provider>

Finally you should inject your store in login form: 最后,您应该以登录形式注入商店:

@inject('globalStore')
class LoginForm extends Component {
...

  render() {
    console.log(this.props.globalStore.loggedIn);
    ...
  }

With these steps you should end up with a working solution. 通过这些步骤,您应该最终得到一个可行的解决方案。 I know MobX can be pain in the ass when you work with it initially. 我知道MobX在最初使用它时可能会感到痛苦。 But then it eases up and you're good to go :). 但是这样可以减轻压力,您就可以开始:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM