简体   繁体   English

如何使用Firebase身份验证在Redux中成功注册用户

[英]How to successfully register users within redux using firebase auth

I keep getting the error undefined when registering a user. 注册用户时,我总是收到undefined的错误。

I'm not sure if react is obtaining the states information correctly. 我不确定react是否正确获取状态信息。 Maybe it could be the onChange value, or maybe im missing something else. 可能是onChange值,或者可能缺少其他内容。

I referenced this 我引用了这个

How to implement Firebase authentication with React Redux? 如何使用React Redux实施Firebase身份验证?

but still unsure, what the error can be. 但仍不确定会出现什么错误。

在此处输入图片说明

It shows that the user has been sign up on the backend like this. 它表明用户已经像这样在后端注册了。

在此处输入图片说明

Demo 演示

https://stackblitz.com/edit/react-h9ekc4 https://stackblitz.com/edit/react-h9ekc4

Actions 操作

export const onEmailSignUpChangeAction = value => ({
    type: EMAIL_SIGN_UP_CHANGE,
    email: value
})

export const onPasswordSignUpChangeAction = value => ({
    type: PASSWORD_SIGN_UP_CHANGE,
    password: value
})



export const onEmptySignUpEmailClick = () => ({
    type: 'EMPTY_SIGN_UP_EMAIL'
})

export const onEmptySignUpPasswordClick = () => ({
    type: 'EMPTY_SIGN_UP_PASSWORD'
})

export const signUp = () => (dispatch, getState) => {
    const {signUpAuth} = getState();
    if (signUpAuth.emailSignUp === '') {
        dispatch(onEmptySignUpEmailClick())
    }
    if (signUpAuth.passwordSignUp === '') { 
        dispatch(onEmptySignUpPasswordClick())
     }
    else {
        firebaseAuth.createUserWithEmailAndPassword(signUpAuth.emailSignUp, signUpAuth.passwordSignUp)
            .then(() => console.log('signUpok'))
                .catch( function (error) {
                        let errorCode = error.code;
                        let errorMessage = error.message;
                        alert(errorMessage)
                });



    }

}

SignUp.js SignUp.js

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { signUp, onEmailSignUpChangeAction, onPasswordSignUpChangeAction } from '../actions/';
class SignUp extends Component {
  state = {
    email: "",
    password: ""
  }

  // onChange = (e) =>{
  //   this.setState({
  //       [e.target.name] : e.target.value
  //   })
  // }
  handleSubmit = (e) => {
    e.preventDefault();
    const register = this.props.signUp();
    console.log(register);
    (register === true) && this.props.history.push('/');
    console.log(this.state)


  }
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-md-6">
            <h1>Sign Up</h1>
            <form onSubmit={this.handleSubmit}>
              <div className="form-group">
                <label htmlFor="exampleInputEmail1">Email address</label>
                <input
                  type="email"
                  className="form-control"
                  id="email"
                  onChange={this.props.onEmailSignUpChangeAction}
                  aria-describedby="emailHelp"
                  value={this.props.emailSignUp}
                  placeholder="Enter email" />
                <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
              </div>
              <div className="form-group">
                <label htmlFor="exampleInputPassword1">Password</label>
                <input
                  type="password"
                  className="form-control"
                  id="password"
                  value={this.props.passwordSignUp}
                  onChange={this.props.onPasswordSignUpChangeAction}
                  placeholder="Password" />
              </div>

              <button type="submit" className="btn btn-primary">Submit</button>
            </form>
          </div>

        </div>
      </div>

    );
  }

}

const mapStateToProps = (state) => ({
  user: state.auth.user,
  emailSignUp: state.signUpAuth.emailSignUp,
  passwordSignUp: state.signUpAuth.passwordSignUp

})

const mapDispatchToProps = (dispatch) => ({
  signUp: () => dispatch(signUp()),
  onEmailSignUpChangeAction: (event) => dispatch(onEmailSignUpChangeAction(event.target.value)),
  onPasswordSignUpChangeAction: (event) => dispatch(onPasswordSignUpChangeAction(event.target.value)),
});


export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SignUp));

Reducers.js Reducers.js

const initialState = {
    emailSignUp: '',
    passwordSignUp: '',
    errorTextEmailSignUp: '',
    errorTextPasswordSignUp: ''

}
export default (state = initialState, action) => {
    switch (action.type) {
        case EMAIL_SIGN_UP_CHANGE:
            return {
                ...state,
                emailSignUp: action.email
            }
        case PASSWORD_SIGN_UP_CHANGE:
            return {
                ...state,
                passwordSignUp: action.password
            }
        case EMPTY_SIGN_UP_EMAIL:
            return {
                ...state,
                errorTextEmailSignUp: 'This field is required'
            }
        case EMPTY_SIGN_UP_PASSWORD:
            return {
                ...state,
                errorTextPasswordSignUp: 'This field is required'
            }
        default:
            return state
    }
}

If you want to pass this.props.emailSignUp and this.props.passwordSignUp into your signUp function you could try: 如果要将this.props.emailSignUpthis.props.passwordSignUp传递到signUp函数中,可以尝试:

export const signUp = (email, password) => { return (dispatch) => {

if (email === '') {
    dispatch({ type: EMPTY_SIGN_UP_EMAIL })
}
else if (password === '') { 
    dispatch({ type: EMPTY_SIGN_UP_PASSWORD })
 }
else {
    firebaseAuth.createUserWithEmailAndPassword(email, password)
        .then(() => console.log('signUpok'))
            .catch( function (error) {
                    let errorCode = error.code;
                    let errorMessage = error.message;
                    alert(errorMessage)
            });



    }
  }
}

Then call your function this.props.signUp(this.props.emailSignUp, this.props.passwordSignUp) 然后调用您的函数this.props.signUp(this.props.emailSignUp, this.props.passwordSignUp)

You are assigning signUp method's return to subscribed variable but that method does return nothing. 您正在将signUp方法的返回值分配给预订的变量,但是该方法不会返回任何内容。 Since its execution is asynchronous, you may need to dispatch an action that will cause a reducer to store the created user in the state when creation has succeeded, then make use of a selector for retrieving that user for instance. 由于其执行是异步的,因此您可能需要调度一个操作,该操作将使reduce在创建成功后将状态为已创建的用户存储在创建的用户中,然后利用选择器来检索该用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 firebase auth 注册用户会抛出错误,但仍然可以正确注册 - Using firebase auth to register a user throws an error, but still registers correctly 身份验证用户在Firestore中注册到收藏集后如何重定向? - How do I redirect after auth users register to collection in Firestore? 如何在React Native中从Firebase Auth调度Redux操作 - How to dispatch Redux action from Firebase auth in React Native 使用 Node js 从 firebase auth 检索多个用户信息 - Retrieve multiple users info from firebase auth using Node js 如何在 Firestore 文档中保存对 Firebase Auth 用户的引用? - How to save references to Firebase Auth Users in a Firestore document? 如何在React Native中从Firebase Auth中检索用户数据? - how to retrieve users data from firebase auth in react native? 尝试在客户端使用 Firebase 身份验证服务注册用户时出错。 Firebase:错误(auth.network-request-failed) - Error when trying to register a user using Firebase Auth service on the client side. Firebase: Error (auth/network-request-failed) 如果注册,请登录用户(Firebase Facebook / google auth) - Sign in user if is register (Firebase facebook/google auth) 如何使用firebase auth实现重新发送OTP - how to achive resend OTP using firebase auth 如何在 firebase 中使用 async 和 await 对用户进行身份验证 - how to auth user using async and await in firebase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM