我正在使用react native和MobX建立密码重置我在重置错误状态时遇到了一些麻烦。我已经尝试了多种解决方案,但似乎都无法正常工作,输入的onChangeText似乎正常,但是我的布尔值不能用于更新UI,我可以看到商店注销了,并且看起来正确,但UI却没有。似乎也正在添加我正在使用的错误消息,也正在使用本机导航:
navigation.navigate('Forgot');
这是我的课:
import React from 'react';
import { action, observable } from 'mobx';
/**
*
*/
class PasswordResetStore {
@observable email = '';
@observable emailError = false;
@action setEmail = (value) => {
console.log(this.emailError);
this.emailError = true;
this.email.value = value;
};
}
const passwordResetStore = new PasswordResetStore();
export const PasswordResetContext = React.createContext(passwordResetStore);
这是我的组件:
import React, { useContext } from 'react';
import { View } from 'react-native';
import { Text, Input, Button } from 'react-native-elements';
import { observer } from 'mobx-react';
import { PasswordResetContext } from '../store/PasswordResetStore';
const PasswordReset = observer(() => {
const store = useContext(PasswordResetContext);
return (
<View>
<View>
<Text h3>Reset your password</Text>
</View>
<View>
<Text>Enter the email your used to sign up</Text>
<Input
onChangeText={store.setEmail}
value={store.email.value}
placeholder="Email"
keyboardType={'email-address'}
autoFocus={true}
autoCorrect={false}
maxLength={256}
autoCapitalize={'none'}
errorMessage={store.emailError ? 'email not found' : ''}
/>
{/*<Button onPress={store.onResetPassword} title="Search" />*/}
</View>
</View>
);
});
export default PasswordReset;
谢谢
初始负载(您看到的是正确的,我应该看到验证错误) [1]:https://i.stack.imgur.com/HYcAy.png
已更新: 添加了一个重置,但仍然没有显示布尔值正确:
useEffect(() => {
return () => {
store.reset();
};
}, []);
@action reset = () => {
this.emailError = false;
};
答案 0 :(得分:1)
如果您使用的是MobX 6,则现在需要在构造函数中使用makeObservable
方法,以实现与以前使用MobX 5相同的装饰器功能:
import { makeObservable } from "mobx"
class PasswordResetStore {
@observable email = '';
@observable emailError = false;
constructor() {
// Just call it here
makeObservable(this);
}
@action setEmail = (value) => {
console.log(this.emailError);
this.emailError = true;
this.email.value = value;
};
}
尽管有新事物可能会让您完全放弃装饰器,makeAutoObservable
:
import { makeAutoObservable } from "mobx"
class PasswordResetStore {
// Don't need decorators now
email = '';
emailError = false;
constructor() {
// Just call it here
makeAutoObservable (this);
}
setEmail = (value) => {
console.log(this.emailError);
this.emailError = true;
this.email.value = value;
};
}
更多信息在这里 https://mobx.js.org/migrating-from-4-or-5.html 和 https://mobx.js.org/react-integration.html