使用React.js实现Redux的建议

时间:2019-03-03 19:45:36

标签: javascript reactjs

这是我第一次在组件中实现redux,但我无法处理,但是我很想知道如何做。

我已经添加了提供程序并将其存储到我的app.js中,并且我停止了为React.js组件添加reducer,选择和其他内容。

这是我的React.js组件。这是一个简单的登录面板,用于检查数据库中是否存在登录名和密码。

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

// Import Material UI
import { withStyles } from '@material-ui/core/styles';
import NavigateNext from '@material-ui/icons/NavigateNext';
import NavigateBefore from '@material-ui/icons/NavigateBefore';

// Import Services
import AuthService from 'services/AuthService';

// Import Components
import Header from 'components/Header';
import Subheading from 'components/Subheading';
import Notification from 'components/Notification';
import Footer from 'components/Footer';

// Import Internationalize
import { FormattedMessage } from 'react-intl';
import messages from './messages';


class LoginPage extends Component {
  constructor() {
    super();

    this.setState = {
      login: '',
      password: '',
      isLoginExist: false,
      loginError: '',
      passwordError: ''
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleFormSubmitLogin = this.handleFormSubmitLogin.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);

    this.Auth = new AuthService();
  }

  componentWillMount() {
    if (this.Auth.loggedIn()) this.props.history.replace('/dashboard');
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value,
      passwordError: '',
      loginError: ''
    });
  }

  handleFormSubmitLogin(e) {
    e.preventDefault();

    this.Auth.isLogin(this.props.login)
      .then((res) => {
        if (res.isLogin) {
          this.setState({
            isLoginExist: true,
            loginError: '',
            password: ''
          });
        } else {
          this.setState({
            login: '',
            loginError: <FormattedMessage {...messages.loginError} />
          });
        }
      })
      .catch(() => {
        this.setState({
          loginError: <FormattedMessage {...messages.loginError} />
        });
      });
  };

  handleFormBack = () => {
    this.setState({
      isLoginExist: false,
      login: '',
      password: '',
      passwordError: ''
    });
  };

  handleFormSubmit(e) {
    e.preventDefault();

    this.Auth.login(this.props.login, this.props.password)
      .then((res) => {
        if (res) {
          this.props.history.replace('/dashboard');
        } else {
          this.setState({
            passwordError: <FormattedMessage {...messages.passwordError} />,
            password: ''
          });
        }
      })
      .catch(() => {
        this.setState({
          passwordError: <FormattedMessage {...messages.loginError} />
        });
      });
  }

  render() {
    console.log(this.props);

    const { classes } = this.props;
    const { isLoginExist, loginError, passwordError } = this.props;
    return (
      <Fragment>
        <FormattedMessage {...messages.helmetLoginTitle}>
          {(title) => <Helmet title={title} />}
        </FormattedMessage>

        <Header />

        <FormattedMessage {...messages.loginToTheSystem}>
          {(title) => <Subheading headerText={title} />}
        </FormattedMessage>

        <div className={classes.pageContainer}>
          <Notification />
          <div className={classes.formContainer}>
            <form noValidate onSubmit={this.handleFormSubmit}>
              {!isLoginExist ? (
                <Fragment>
                  <div className={classes.textField}>
                    <FormattedMessage {...messages.numberId} />
                  </div>
                  {[
                    <Fragment key={1}>
                      <FormattedMessage {...messages.inputNumber}>
                        {(placeholder) => (
                          <input
                            className={classNames(classes.formItem, {
                              [classes.formError]: loginError
                            })}
                            placeholder={placeholder}
                            name="login"
                            type="number"
                            onChange={this.handleChange}
                            onKeyPress={(ev) => {
                              if (ev.key === 'Enter') {
                                ev.preventDefault();
                                this.handleFormSubmitLogin(ev);
                              }
                            }}
                          />
                        )}
                      </FormattedMessage>
                      {loginError ? (
                        <div className={classes.textError}>{loginError}</div>
                      ) : null}
                    </Fragment>
                  ]}
                  <button
                    type="button"
                    className={classes.formSubmit}
                    onClick={this.handleFormSubmitLogin}
                  >
                    <span className={classes.buttonText}>
                      <FormattedMessage {...messages.nextText} />
                    </span>
                    <NavigateNext />
                  </button>
                </Fragment>
              ) : (
                <Fragment>
                  <div className={classes.textField}>
                    <FormattedMessage {...messages.accessCode} />
                  </div>
                  {[
                    <Fragment key={2}>
                      <FormattedMessage {...messages.inputPassowrd}>
                        {(placeholder) => (
                          <input
                            className={classNames(classes.formItem, {
                              [classes.formError]: passwordError
                            })}
                            placeholder={placeholder}
                            name="password"
                            type="password"
                            onChange={this.handleChange}
                            onKeyPress={(ev) => {
                              if (ev.key === 'Enter') {
                                ev.preventDefault();
                                this.handleFormSubmit(ev);
                              }
                            }}
                          />
                        )}
                      </FormattedMessage>
                      {passwordError ? (
                        <div className={classes.textError}>{passwordError}</div>
                      ) : null}
                    </Fragment>
                  ]}
                  <button className={classes.formSubmit} type="submit">
                    <span className={classes.buttonText}>
                      <FormattedMessage {...messages.inputLogin} />
                    </span>
                  </button>
                  <button type="button" onClick={this.handleFormBack}>
                    <NavigateBefore />
                    <span className={classes.buttonText}>
                      <FormattedMessage {...messages.backText} />
                    </span>
                  </button>
                </Fragment>
              )}
              <br />
            </form>
          </div>
          <Footer />
        </div>
      </Fragment>
    );
  }
}

LoginPage.propTypes = {
  classes: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
  replace: PropTypes.string
};

const mapStateToProps = (state) => ({
  login: state.login,
  password: state.password,
  isLoginExist: state.isLoginExist,
  loginError: state.loginError,
  passwordError: state.passwordError
});

export default withStyles(styles)(
  withRouter(connect(mapStateToProps)(LoginPage))
);

0 个答案:

没有答案