React Native 和 MobX:useContext 不会将更改重新呈现到屏幕中

React Native & MobX: useContext doesn't re-render the change into the screen

我一直在尝试使用mobX应用在React Native Functional Component上。 所以我使用这两个库 - mobx 和 mobx-react-lite。

我制作了一个简单的计数器应用程序,并且还使用了上下文挂钩。 增加该值后,它不会应用在屏幕上。但是,它出现在我的控制台上。 在我通过保存刷新代码后显示更改(我没有更改代码)

如何解决这个问题?

App.js

import { StyleSheet, Text, View,Button } from 'react-native';
import { CounterStoreContext } from './components/CounterStore';
  
import { observer } from "mobx-react-lite";
import React, { useContext, useState } from "react";

const App = observer(() => {
  // const [count, setCount] = useState(0);
  const counterStore = useContext(CounterStoreContext)
  return (
    <View style={styles.container}>
      <Text style={styles.welcome}>Welcome</Text>
      <Text style={styles.text}>Just Press the damn button</Text>
      {/* <Text style={styles.text}>{count}</Text> */}
      {/* <Button title="Increase" onPress={()=>{setCount(count+1)}}/> */}
      <Text style={styles.text}>{counterStore.count}</Text>
      <Button title="Increase" onPress={()=>{
        counterStore.count++;
        console.log(counterStore.count)
        // setCount(counterStore.count)
      }}/>      
    </View>
  );
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  welcome:{
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  text:{
    fontSize: 14,
    textAlign: 'center',
  },
});

export default App;

CounterStore.js

import { observable, observe } from "mobx";
import { createContext } from "react";

class CounterStore {
    @observable count = 0;
}

export const CounterStoreContext = createContext(new CounterStore())

Since MobX 6 the @observable decorator is not enough. You need to use makeObservable / makeAutoObservable 在构造函数中也是如此。

class CounterStore {
    @observable count = 0;

    constructor() {
        makeAutoObservable(this);
    }
}