我是新来的反应,我想在反应与火力点进行身份验证。我创建了一个高阶组件基本上与用户的状态充实组件,如果用户进行身份验证或不验证。下面是我WithAuthentication.js和组件本身的componentDidmount我想检查用户是否isSignedin。
import React, { Component } from 'react';
import { FirebaseContext } from '../firebase';
export default WrappedComponent => {
class WithAuthentication extends Component {
state = {
user:null,
isSignedin:false
};
componentDidMount() {
let firebase = this.context
firebase.auth().onAuthStateChanged(user => {
if (user) {
console.log(user)
this.setState({
user: user.providerData,
isSignedin: true
});
console.log(this.state.isSignedin);
} else {
console.info('Must be authenticated');
}
});
}
render() {
return this.state.isSignedin ? (
<WrappedComponent
{...this.props}
user={this.state.user}
isSignedin={this.state.isSignedin}
/>
) : (
<WrappedComponent
{...this.props}
user={"NOTUSER"}
isSignedin={this.state.isSignedin}
/>
);
}
}
WithAuthentication.contextType =FirebaseContext
return WithAuthentication;
};
组件文件。
componentDidMount() {
let firebase = this.context
console.log(this.props);
const db = firebase.firestore();
var turmarkers =[];
this.setState({isSignedin:this.props.isSignedin})
console.log(this.state.isSignedin);
this.state.isSignedin ?
db.collection("Markets").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
var mdata = doc.data()
mdata["key"] = doc.id
turmarkers.push(mdata)
});
this.setState({
mapdata:turmarkers
});
})
:
console.log("this is not a user")
}
在第一渲染子组件获得虚假标签和WithAuthentication.js改变后它的isSignedin的状态设置为true。我想到孩子组件状态得到尽快包装状态得到更新更新。但它不会发生。在包装部件的状态被更新,但它不是传递给孩子。
我曾尝试直接检查道具isSignedin,看它是否在孩子的变化,并没有。
我想我找到了答案,关键是要检查认证做或不该再检查,如果认证验证用户的signedin与否。下面是它被回答。