提交后,表单未设置为null

时间:2020-08-17 05:29:18

标签: reactjs firebase google-cloud-firestore firebase-authentication react-functional-component

我是React的初学者,遇到了一些问题。我正在使用Firebase通过电子邮件和密码进行注册。但是在使用此功能时,我遇到了一些问题:-

  1. 提交后表单未设置为null(可能以catch块结尾)。
  2. 在将凭据保存到FireStore中时,displayName设置为null(有时保存到数据库中,有时不保存)。

App.js

import React from 'react';
import './App.css';
import {Route} from 'react-router-dom';
import HomePage from './Pages/HomePage/Homepage.component';
import ShopComponent from './Pages/Shop/shop.component';
import Header from './Components/Headers/header.component';
import {Switch} from 'react-router-dom';
import {useEffect} from 'react';
import {useState} from 'react';
import {auth} from './Components/FireBase/firebase.util';
import {createUserProfileDocument} from './Components/FireBase/firebase.util';

import SignInAndSignUpPage from './Pages/Sign-In and Sign-Up/sign-in-and-sign-up.component';

function App() {
  const [user,setUser] =useState(null);

  useEffect(
    ()=>{
        const abortController = new AbortController();
        const signal = abortController.signal;


 
auth.onAuthStateChanged(async userAuth => {
  if (userAuth) { 
    const userRef = await createUserProfileDocument(userAuth);
    userRef.onSnapshot(snapShot => { 
      setUser({
       
          id: snapShot.id,
          ...snapShot.data()
        }
      ,()=>console.log(user,App.js));

      
    });
  }
})
return function cleanup()
{
    abortController.abort();
} 
},[]);

    function logout()
  {
     setUser(null);
   }
  return (

<div>
  <Header user={user} logout={logout}/>
  <Switch>
  <Route exact path="/" component={HomePage}/>
  <Route path="/shop" component={ShopComponent} />
  <Route path="/signin" component={SignInAndSignUpPage}/>
  </Switch>
  {console.log(user)}
</div>
  );
}

export default App;

SignUp.js

import React from 'react';

import FormInput from '../FormInput/FormInput.component';
import CustomButton from '../custom-button/custom-button.component';

import { auth, createUserProfileDocument } from '../FireBase/firebase.util';
import {useState} from 'react';

import './sign-up.styles.scss';

export default function SignUp() {

    const [User,setUser] = useState({
  displayName: '',
  email: '',
  password: '',
  confirmPassword: ''
});


  const handleSubmit = async event => {
    event.preventDefault();



if (User.password !== User.confirmPassword) {
  alert("passwords don't match");
      return;
}
console.log(User);
try {
  const { user } = await auth.createUserWithEmailAndPassword(
    User.email,
    User.password,
    
  ).then(function(result) {
    console.log(result);
    return result.user.updateProfile({
      displayName: User.displayName
    })
  }).catch(function(error) {
    console.log(error);
  });
console.log(user);

  await createUserProfileDocument(user,User.displayName);
  
  setUser({
    displayName: "",
    email: "",
    password: "",
    confirmPassword: ""
  });
  console.log(User);
} catch (error) {
  console.error(error);
}
  };

  function handleChange(event) {
const { name, value } = event.target;

setUser({...User,[name]:value});
  };

return (
  <div className='sign-up'>
    <h2 className='title'>I do not have a account</h2>
    <span>Sign up with your email and password</span>
    <form className='sign-up-form' onSubmit={handleSubmit}>
      <FormInput
        type='text'
        name='displayName'
        value={User.displayName}
        handleChange={handleChange}
        label='Display Name'
        required
      />
      <FormInput
        type='email'
        name='email'
        value={User.email}
        handleChange={handleChange}
        label='Email'
        required
      />
      <FormInput
        type='password'
        name='password'
        value={User.password}
        handleChange={handleChange}
        label='Password'
        required
      />
      <FormInput
        type='password'
        name='confirmPassword'
        value={User.confirmPassword}
        handleChange={handleChange}
        label='Confirm Password'
        required
      />
      <CustomButton type='submit'>SIGN UP</CustomButton>
    </form>
  </div>
    );

}

Firebase.util.js

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';

var firebaseConfig = {
    apiKey: "AIzaSyCeHYh9WYswWRO69UF8wjTfhK8YXdc7M10",
    authDomain: "clothingecom-signin.firebaseapp.com",
    databaseURL: "https://clothingecom-signin.firebaseio.com",
    projectId: "clothingecom-signin",
    storageBucket: "clothingecom-signin.appspot.com",
    messagingSenderId: "150267270963",
    appId: "1:150267270963:web:e188327556e8ffbb099046",
    measurementId: "G-Z1CVYEVYKN"
  };

firebase.initializeApp(firebaseConfig);



export const createUserProfileDocument = async (userAuth, additionalData) => {
  if (!userAuth) return; 

   console.log(userAuth);
  const snapShot = await userRef.get();
   console.log(userRef);
   console.log(snapShot);
  if (!snapShot.exists) { 
    const {displayName,  email } = userAuth; 
    const createdAt = new Date();
    try {
      await userRef.set({
        displayName,
        email,
        createdAt,
        ...additionalData
      });
    } catch (error) {
      console.log('error creating user', error.message);
    }
  }

  return userRef;
};

export const auth = firebase.auth();
export const firestore = firebase.firestore();

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider);

export default firebase;

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

这应该有效!

5 minute