MobX + React Native 不重新渲染

MobX + React Native not re-rendering

我正在使用 React Native 和 MobX 构建密码重置我在重置错误状态时遇到了一些麻烦。我尝试了多种解决方案,但 none 似乎有效,输入的 onChangeText 似乎有效但我的布尔值无法更新 UI,我可以看到商店注销并且这似乎是正确的,但 UI 似乎没有添加我正在使用的错误消息也使用反应本机导航:

navigation.navigate('Forgot');

这是我的 class:

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;
  };

如果您使用的是 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.htmlhttps://mobx.js.org/react-integration.html