无法使用Meteor和React获得用户注册的rif

时间:2017-08-05 09:41:03

标签: javascript reactjs meteor

我是Meteor的新手,我正在研究它。实际上,我正在创建一个用户登录,注册页面,每个注册用户都有一个私人控制面板。

我能够正确注册和登录,但我有两个不同的问题:

  1. 在创建用户时,我无法将信息保存到配置文件对象,看起来根本不会触发onCreateUser方法。
  2. 当用户登录时,我在“控制面板”页面中获取用户信息,但如果我刷新页面,即使用户仍然登录,我也不会再收到这些信息。
  3. 这是代码。

    /imports/api/users.js

    import { Meteor } from 'meteor/meteor';
    import { Accounts } from 'meteor/accounts-base';
    
    if (Meteor.isServer) {
      Meteor.publish('userData', () => {
        return Meteor.users.find({ _id: Meteor.userId() }, {
          fields: { profile: 1 }
        });
      });
    }
    
    Accounts.onCreateUser((options, user) => {
      user.profile = options.profile || {};
      user.profile.accountType = options.accountType;
    
      return user;
    });
    

    /imports/ui/Signup.js

    import React, { Component } from 'react';
    import { Link } from 'react-router-dom';
    import { Meteor } from 'meteor/meteor';
    import { Accounts } from 'meteor/accounts-base';
    import Joi from 'joi';
    import validation from 'react-validation-mixin';
    import strategy from 'joi-validation-strategy';
    import classnames from 'classnames';
    
    import history from '../../utils/history';
    
    class Signup extends Component {
      constructor(props) {
        super(props);
    
        this.validatorTypes = {
          accountType: Joi.string().required().label('Account type'),
          email: Joi.string().email().label('Email'),
          password: Joi.string().required().min(6).label('Password'),
          confirmPassword: Joi.string().required().min(6).valid(Joi.ref('password')).label('Confirm password').options({
            language: {
              any: {
                allowOnly: '!!Passwords do not match'
              }
            }
          })
        };
    
        this.getValidatorData = this.getValidatorData.bind(this);
        this.renderHelpText = this.renderHelpText.bind(this);
        this.getClasses = this.getClasses.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    
        this.state = {
          serverError: ''
        };
      }
    
      componentWillMount() {
        if (Meteor.userId()) {
          history.replace('/');
        }
      }
    
      getValidatorData() {
        return {
          accountType: this.refs.accountType.value,
          email: this.refs.email.value,
          password: this.refs.password.value,
          confirmPassword: this.refs.confirmPassword.value
        };
      }
    
      renderHelpText(message) {
        return (
          <span className='validation-error-message'>{message}</span>
        );
      }
    
      getClasses(field) {
        return classnames({
          'form-group': true,
          'has-error': !this.props.isValid(field)
        });
      }
    
      onSubmit(e) {
        e.preventDefault();
    
        const onValidate = error => {
          if (!error) {
            let accountType = this.refs.accountType.value;
            let email = this.refs.email.value.trim();
            let password = this.refs.password.value.trim();
            let confirmPassword = this.refs.confirmPassword.value.trim();
    
            Accounts.createUser({ email, password, accountType }, (err) => {
              if (err) {
                this.setState({
                  serverError: err.reason
                });
              } else {
                this.setState({
                  serverError: ''
                });
                history.replace('/account');
              }
            });
          }
        };
    
        this.props.validate(onValidate);
      }
    
      render() {
        return (
          <div className="form-container">
            <h3>Create Account</h3>
            <form onSubmit={this.onSubmit}>
              <div className={this.getClasses('accountType')}>
                <select
                  className="form-control"
                  name="accountType"
                  ref="accountType"
                  placeholder="Account type"
                  onChange={this.props.handleValidation('accountType')}
                >
                  <option value="">Select account type</option>
                  <option value="student">Sudent</option>
                  <option value="teacher">Teacher</option>
                  <option value="guest">Guest</option>
                </select>
                {this.renderHelpText(this.props.getValidationMessages('accountType')[0])}
              </div>
              <div className={this.getClasses('email')}>
                <input
                  className="form-control"
                  type="text"
                  name="email"
                  ref="email"
                  placeholder="email address"
                  onChange={this.props.handleValidation('email')}
                />
                {this.renderHelpText(this.props.getValidationMessages('email')[0])}
              </div>
              <div className={this.getClasses('password')}>
                <input
                  className="form-control"
                  type="password"
                  name="password"
                  ref="password"
                  placeholder="password"
                  onChange={this.props.handleValidation('password')}
                />
                {this.renderHelpText(this.props.getValidationMessages('password')[0])}
              </div>
              <div className={this.getClasses('confirmPassword')}>
                <input
                  className="form-control"
                  type="password"
                  name="confirmPassword"
                  ref="confirmPassword"
                  placeholder="confirm password"
                  onBlur={this.props.handleValidation('confirmPassword')}
                />
                {this.renderHelpText(this.props.getValidationMessages('confirmPassword')[0])}
              </div>
              <button className="btn btn-dark" type="submit">Create</button>
            </form>
            <div className="meta">
              <p>Already have an account? <Link to="/login">Login</Link></p>
            </div>
          </div>
        );
      }
    };
    
    export default validation(strategy)(Signup);
    

    我期望在创建新用途时,名为users.js的{​​{1}}中的方法被触发,Accounts.onCreateUser信息会添加到个人资料中。它没有发生。

    我还希望始终在控制面板中检索当前登录的用户信息。以下是控制面板组件:

    /imports/ui/Account.js

    导入React,{Component}来自&#39;反应&#39 ;; 从流星/流星&#39 ;;

    导入{Meteor}

    从&#39; ../../ utils / history&#39;;

    导入历史记录
    accountType

    我做错了什么?

1 个答案:

答案 0 :(得分:0)

There are several things wrong with your code but they can easily be fixed.

  1. Accounts.onCreateUser is a server only function. Insert a console.log into the function just to make sure it is called. If not, make sure that you import '/imports/api/users.js' in your main.js.

  2. Accounts.createUser accepts only 4 keys in the options object: username, email, password and profile (see docs). That is why accountType is not passed to onCreateUser. Do Accounts.createUser({ email, password, profile: { accountType } }, ...). Then in onCreateUser you find the accountType under options.profile.accountType.

  3. To subscribe to data you should use meteors createContainer component. See the guide. That will solve the problem that your data is not yet available when the component mounts and will rerender it when the data is ready.