Реагировать на родной опорожнение реквизита - PullRequest
0 голосов
/ 20 октября 2018

У меня есть экран с кнопками входа и регистрации.Когда пользователь нажимает SigninButton, я отправляю его на экран входа.На экране входа в систему есть два текстовых ввода, которые получают электронную почту и пароль от пользователя.Если это успешно, пользователь отправляется на главный экран.Если нет, я выкидываю текст ошибки.Но если пользователь вернется из панели навигации и вернется к экрану входа, там по-прежнему будут отображаться ввод электронной почты и сообщение об ошибке.Я использую Redux, я не могу очистить реквизиты, которые содержат электронную почту и текст ошибкиЯ пробовал componentWillUnmount, componentWillMount и т. Д., Но все еще не могу найти правильное место, чтобы очистить эти реквизиты.Это код на экране входа в систему;

class LoginScreen extends Component {

  componentWillReceiveProps(nextProps) {
    this.onAuthComplete(nextProps);
  }

  onAuthComplete(props) {
    if (props.user) {
      this.props.navigation.navigate('main');
    }
  }

  render() {
    return(
      <View style={styles.container}>
        <SigninForm />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  ........
  }
});

const mapStateToProps = ({ auth }) => {
  const { user, email, error } = auth;

  return { user, email, error };
}

export default connect(mapStateToProps, { emailChanged, loginUser })(LoginScreen);

, а также этот код в редукторе;

import ......

const INITIAL_STATE = {
  email: '',
  password: '',
  user: null,
  error: '',
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case EMAIL_CHANGED:
      return {...state, email: action.payload };
    case PASSWORD_CHANGED:
      return {...state, password: action.payload };
    case LOGIN_USER:
      return {...state, error: ''};
    case LOGIN_USER_SUCCESS:
      return {...state, ...INITIAL_STATE, user: action.payload};
    case LOGIN_USER_FAIL:
      return {...state, error: 'Authentication Failed', password: ''};
    default:
      return state;
  }
};

А вот код SigninForm;

import React, { Component } from 'react';
import { View, Dimensions, Text } from 'react-native';
import { connect } from 'react-redux';
import { FormInput, FormLabel } from 'react-native-elements';
import { AuthButton } from './';
import { emailChanged, passwordChanged, loginUser } from '../actions';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

class SigninForm extends Component {

  onEmailChange(text) {
    this.props.emailChanged(text);
  }

  onPasswordChange(text) {
    this.props.passwordChanged(text);
  }

  onButtonPress() {
      const { email, password } = this.props;
      this.props.loginUser({ email, password });
  }

  render() {
    return(
      <View style={styles.viewStyle}>
        <FormLabel labelStyle={styles.labelStyle}>Email</FormLabel>
        <FormInput
          placeholder='Enter your email'
          keyboardType="email-address"
          containerStyle={styles.containerStyle}
          inputStyle={styles.inputStyle}
          onChangeText={this.onEmailChange.bind(this)}
          value={this.props.email}
        />
        <FormLabel labelStyle={styles.labelStyle}>Password</FormLabel>
        <FormInput
          placeholder='Enter a password'
          secureTextEntry={true}
          containerStyle={styles.containerStyle}
          inputStyle={styles.inputStyle}
          onChangeText={this.onPasswordChange.bind(this)}
          value={this.props.password}
        />
        <Text style={styles.errorTextStyle}>
          {this.props.error}
        </Text>
        <AuthButton
          title='Sign In'
          backgroundColor='#eb4454'
          onPress={this.onButtonPress.bind(this)}
        />
      </View>
    );
  }
}
const styles = {
  viewStyle: {
    top: SCREEN_HEIGHT * -0.15
  },
  containerStyle: {
    marginBottom: 10,
    width: SCREEN_WIDTH * 0.80,
    borderBottomColor: '#3c143c'
  },
  labelStyle: {
    color: '#3c143c',
    fontFamily: 'System',
    fontSize: 20
  },
  inputStyle: {
    color: '#3c143c',
    fontFamily: 'System',
    fontSize: 20
  },
  errorTextStyle: {
    fontSize: 20,
    alignSelf: 'center',
    color: 'red'
  }
}

const mapStateToProps = ({ auth }) => {
    const { email, password, error } = auth;

    return { email, password, error };
}

export default connect(mapStateToProps, { emailChanged, passwordChanged, loginUser })(SigninForm);

1 Ответ

0 голосов
/ 20 октября 2018

Я сделал это в методе componentWillMount.Я вызвал действие, чтобы вызвать редуктор, чтобы обновить состояния соответствующих реквизитов.Вот фрагмент кода в моем компоненте:

import React, { Component } from 'react';
import { View, Dimensions, Text } from 'react-native';
import { connect } from 'react-redux';
import { FormInput, FormLabel } from 'react-native-elements';
import { AuthButton } from './';
import { emailChanged, passwordChanged, loginUser, emptyInput } from '../actions';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

class SigninForm extends Component {
  componentWillMount() {
    //used for empty email and error text when user go back and forth
    const { email, error } = this.props;
    this.props.emptyInput(email, error);
  }

  onEmailChange(text) {
    this.props.emailChanged(text);
  }

  onPasswordChange(text) {
    this.props.passwordChanged(text);
  }

  onButtonPress() {
      const { email, password } = this.props;
      this.props.loginUser({ email, password });
  }

  render() {
    console.log("render ediyorum");
    return(
      <View style={styles.viewStyle}>
        <FormLabel labelStyle={styles.labelStyle}>Email</FormLabel>
        <FormInput
          placeholder='Enter your email'
          keyboardType="email-address"
          containerStyle={styles.containerStyle}
          inputStyle={styles.inputStyle}
          onChangeText={this.onEmailChange.bind(this)}
          value={this.props.email}
        />
        <FormLabel labelStyle={styles.labelStyle}>Password</FormLabel>
        <FormInput
          placeholder='Enter a password'
          secureTextEntry={true}
          containerStyle={styles.containerStyle}
          inputStyle={styles.inputStyle}
          onChangeText={this.onPasswordChange.bind(this)}
          value={this.props.password}
        />
        <Text style={styles.errorTextStyle}>
          {this.props.error}
        </Text>
        <AuthButton
          title='Sign In'
          backgroundColor='#eb4454'
          onPress={this.onButtonPress.bind(this)}
        />
      </View>
    );
  }
}
const styles = {
  viewStyle: {
    top: SCREEN_HEIGHT * -0.15
  },
  containerStyle: {
    marginBottom: 10,
    width: SCREEN_WIDTH * 0.80,
    borderBottomColor: '#3c143c'
  },
  labelStyle: {
    color: '#3c143c',
    fontFamily: 'System',
    fontSize: 20
  },
  inputStyle: {
    color: '#3c143c',
    fontFamily: 'System',
    fontSize: 20
  },
  errorTextStyle: {
    fontSize: 20,
    alignSelf: 'center',
    color: 'red'
  }
}

const mapStateToProps = ({ auth }) => {
    const { email, password, error } = auth;

    return { email, password, error };
}

export default connect(mapStateToProps, { emailChanged, passwordChanged, loginUser, emptyInput })(SigninForm);

Это код создателя действия emptyInput;

export const emptyInput = (email, error) => {
  return(dispatch) => {
    dispatch({ type: EMPTY_INPUT });
  }
};

И, наконец, код редуктора, выполняющий реальную работу;

import {
  EMAIL_CHANGED,
  PASSWORD_CHANGED,
  CREATE_USER,
  CREATE_USER_SUCCESS,
  CREATE_USER_FAIL,
  LOGIN_USER,
  LOGIN_USER_FAIL,
  LOGIN_USER_SUCCESS,
  EMPTY_INPUT
} from '../actions/types';

const INITIAL_STATE = {
  email: '',
  password: '',
  user: null,
  error: '',
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case EMAIL_CHANGED:
      return {...state, email: action.payload };
    case PASSWORD_CHANGED:
      return {...state, password: action.payload };
    case CREATE_USER:
      return {...state, error: '' };
    case CREATE_USER_SUCCESS:
      return {...state, ...INITIAL_STATE, user: action.payload};
    case CREATE_USER_FAIL:
      return {...state, error: 'Authentication Failed!', password: ''};
    case LOGIN_USER:
      return {...state, error: ''};
    case LOGIN_USER_SUCCESS:
      return {...state, ...INITIAL_STATE, user: action.payload};
    case LOGIN_USER_FAIL:
      return {...state, error: 'Authentication Failed', password: ''};
    case EMPTY_INPUT:
        return {...state, ...INITIAL_STATE};
    default:
      return state;
  }
};
...