Mobx未更新React原生元素

zour9fqk  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(153)

我是react和mobx的新手。我尝试使用mobx来更新一个简单的计数器并显示计数值。当我点击“添加”按钮时,我可以在日志中看到 counterStore.count 正在增加,但 * * 中显示的计数器仍然等于0。
你能告诉我到底怎么了吗?

索引.tsx

import { observer } from "mobx-react";
import React from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import CounterStore from './stores/CounterStore';

export function App() {
  const counterStore = new CounterStore(0);

  return (
    <View style={styles.container}>
      <View style={styles.wrapper}>
        <Text>{counterStore.count}</Text>
            <Button
                title="Add"
                onPress={() => {
                    counterStore.addToCount();
                    console.log("count = ", counterStore.count);
                    
                }}
            />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    height: "100%"
  },
  wrapper: {
    backgroundColor: "#F5FCFF",
    width: "100%",
    maxWidth: 425
  }
});

export default observer(App);

柜台商店.ts

import { action, makeObservable, observable } from "mobx";

class CounterStore {
  @observable count: number;

  constructor(count: number){
    this.count = count
    makeObservable(this);
  }

  @action
  addToCount(){
    this.count++;
  }
}

export default CounterStore;

输出日志(& L)

output

bkhjykvo

bkhjykvo1#

我试图根据 Jay Vaghasiya 的答案改进我的代码,但仍然得到相同的行为。

柜台商店.ts

import { action, makeObservable, observable } from "mobx";
import React from "react";

class CounterStore {
  count = 0;

  constructor(){
    makeObservable(this), {count: observable};
  }

  @action
  addToCount(){
    this.count++;
  }
}

export const CounterStoreContext = React.createContext(new CounterStore());

索引.tsx

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

const App = observer(() => {
  const counterStore = React.useContext(CounterStoreContext);

  return (
    <View style={styles.container}>
        <Text>{counterStore.count}</Text>
            <Button
                title="Add"
                onPress={() => {
                    counterStore.addToCount();
                    console.log("count = ", counterStore.count);
                    
                }}
            />
    </View>
  );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    height: "100%",
  },
  wrapper: {
    backgroundColor: "#F5FCFF",
    width: "100%",
    maxWidth: 425
  }
});

export default App;

相关问题