当我尝试从uiConfig内部调用this.setState()时,“ this”出现为未定义状态(它指的是我想的uiConfig对象?)
我尝试创建一个内部调用this.setState的新函数,但是遇到了同样的“ this is undefined”错误。
那么调用this.setState并更新组件的正确方法是什么?
import React from 'react';
import firebase from 'firebase';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
export default class Signin extends React.Component {
constructor(props) {
super(props);
this.state = {
isNewUser: 'false'
};
}
uiConfig = {
signInFlow: "popup",
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID
],
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl){
// Check if its a new user
const user = authResult.user;
const isNewUser = authResult.additionalUserInfo.isNewUser;
if (isNewUser) {
this.setState({ // this is undefined
isNewUser: true
});
const db = firebase.firestore();
const usersRef = db.collection("users");
usersRef.doc(user.uid).set({
username: null,
email: user.email,
photoURL: user.photoURL,
emailVerified: user.emailVerified
})
}
}
}
}
componentDidMount = () => {
firebase.auth().onAuthStateChanged(user => {
this.props.changeSignedInStatus(user);
})
}
render() {
let promptUsername = <></>;
if(this.state.isNewUser) {
console.log('new user')
}
return (
<div className='login'>
<form action="" className='signin-form'>
<h1>Sign in</h1>
<StyledFirebaseAuth
uiConfig={this.uiConfig}
firebaseAuth={firebase.auth()}
/>
{promptUsername}
</form>
</div>
);
}
}