【问题标题】:Mobx store doesn't trigger re-render on react-native projectMobx 商店不会触发 react-native 项目的重新渲染
【发布时间】:2020-11-06 04:11:04
【问题描述】:

我尝试了解如何将 MobX 与 React Native 结合使用。 我试图在 GH 中找到一些例子,但它们已经很老了。 (2-3岁)。

我想在 Expo Bare (ExpoKit) 上编写应用程序,但我不明白为什么当我更改 MobX @observables 时我的组件没有重新呈现。

我为我的问题创建了一个零食:https://snack.expo.io/@krasov/mobx-reproduction

Idk,可能是我错过了文档,但我无法弄清楚这里的问题。

【问题讨论】:

    标签: react-native expo mobx mobx-react


    【解决方案1】:

    如果您使用的是 MobX 6,那么您现在需要在构造函数中使用 makeObservable 方法来实现与之前使用 MobX 5 的装饰器相同的功能:

    import { makeObservable } from "mobx"
    
    class Store {
      @observable string = 'Test String';
      @action setString = (string) => {
        this.string = string;
        console.log(`new value = ${this.string}`);
      };
    
      constructor() {
        // Just call it here
        makeObservable(this);
      }
    }
    

    虽然有新的东西可能会让你完全放弃装饰器,makeAutoObservable:

    import { makeAutoObservable } from "mobx"
    
    class Store {
      // Don't need decorators now
      string = 'Test String';
      setString = (string) => {
        this.string = string;
        console.log(`new value = ${this.string}`);
      };
    
      constructor() {
        // Just call it here
        makeAutoObservable (this);
      }
    }
    

    更多信息在这里 https://mobx.js.org/migrating-from-4-or-5.htmlhttps://mobx.js.org/react-integration.html

    【讨论】:

    • 非常感谢。这样就解决了问题。我曾经在 YouTube 上观看过 MobX 指南,它们已经很老了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多