无法从 mobx 存储中获取更新值
Unable to get an updated value from mobx store
我只是在试用 mobx,我有一个简单的组件和一个商店。每当按下按钮时,我希望它的文本会更新为新的时间戳。但是,这不会发生,我不知道为什么。这是代码:
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Card, Button } from 'react-native-paper';
import { observer } from "mobx-react";
import { makeAutoObservable } from "mobx"
class State {
timestamp = Date.now();
constructor() {
makeAutoObservable(this)
}
setTimestamp() {
this.timestamp = Date.now();
}
}
const state = new State();
const App = observer(() => {
const { timestamp, setTimestamp } = state;
return (
<View style={s.root}>
<Button onPress={setTimestamp}>
{timestamp}
</Button>
</View>
);
});
const s = StyleSheet.create({
root: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});
export default App;
也可以在这里找到:https://snack.expo.io/@pavermakov/react-native-mobx
我使用以下依赖项:
"mobx": "6.0.1",
"mobx-react": "7.0.0"
我是不是漏掉了什么?
加上这段代码:
<Button onPress={setTimestamp}>
您正在丢失 State
class 实例的 this
上下文。单击按钮时 this
实际上指的是 Button
元素,因此没有 Button.timestamp
更改。
解决此问题的最简单方法是 bind
setTimestamp
返回 state
class,如下所示:
<Button onPress={setTimestamp.bind(state)}>
我只是在试用 mobx,我有一个简单的组件和一个商店。每当按下按钮时,我希望它的文本会更新为新的时间戳。但是,这不会发生,我不知道为什么。这是代码:
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Card, Button } from 'react-native-paper';
import { observer } from "mobx-react";
import { makeAutoObservable } from "mobx"
class State {
timestamp = Date.now();
constructor() {
makeAutoObservable(this)
}
setTimestamp() {
this.timestamp = Date.now();
}
}
const state = new State();
const App = observer(() => {
const { timestamp, setTimestamp } = state;
return (
<View style={s.root}>
<Button onPress={setTimestamp}>
{timestamp}
</Button>
</View>
);
});
const s = StyleSheet.create({
root: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});
export default App;
也可以在这里找到:https://snack.expo.io/@pavermakov/react-native-mobx
我使用以下依赖项:
"mobx": "6.0.1",
"mobx-react": "7.0.0"
我是不是漏掉了什么?
加上这段代码:
<Button onPress={setTimestamp}>
您正在丢失 State
class 实例的 this
上下文。单击按钮时 this
实际上指的是 Button
元素,因此没有 Button.timestamp
更改。
解决此问题的最简单方法是 bind
setTimestamp
返回 state
class,如下所示:
<Button onPress={setTimestamp.bind(state)}>