我是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)
1条答案
按热度按时间bkhjykvo1#
我试图根据 Jay Vaghasiya 的答案改进我的代码,但仍然得到相同的行为。
柜台商店.ts
索引.tsx