我目前正在使用 Mobx 6.9.0 和 React Native/Expo 创建一个示例应用程序。 这是我当前的设置:
App.tsx
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from "mobx-react";
import State from "./src/state";
import Sample from './src/sample/components/Sample';
export default function App() {
return (
<Provider store={State}>
<View style={styles.container}>
<Sample/>
<StatusBar style="auto" />
</View>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
示例.tsx
import { View, Text, Button, TextInput } from 'react-native'
import React from 'react'
import { observer, inject } from "mobx-react";
function Sample(props: any){
const { count, updateCount} = props.store
console.log(count)
return (
<View style={{alignItems: 'center'}}>
<Text style={{fontSize:100}}>{count}</Text>
<Button
title='Press Me'
onPress={updateCount}
/>
</View>
)
}
export default inject('store')(observer(Sample))
状态.ts
import { makeObservable, observable, action, computed } from "mobx";
class State {
constructor(){
console.log('New Store')
makeObservable(this, {
count: observable,
text: observable,
currentCount: computed,
updateCount: action
})
}
count = 0
text = ''
get currentCount(): number {
return this.count
}
updateCount(): void {
this.count += 1
console.log(this.count)
}
}
export default State
每当我按下按钮时,我都希望 updateCount 更新并重新呈现我的 Sample.tsx 组件。然而,这并没有发生;并且 'console.log(this.count)' 返回为未定义。
我希望显示的计数会自动更新,但我没有看到我遗漏了什么。有人能够深入了解这个问题吗?谢谢!