我正在使用一个简单的React应用程序设置Firebase身份验证,以便登录后即可重定向到新页面(导航栏也会更改)。我在这里(@ https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/#react-firebase)遵循Robin Wieruch的指南。
我已经设置了Firebase,使其成为一个上下文实例,只需要实例化一次。我正在使用onAuthStateChanged确定用户是否已登录,因此将相应地更改导航栏。
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import App from './components/App';
import Firebase, { FirebaseContext } from './components/Firebase';
ReactDOM.render(
<FirebaseContext.Provider value={new Firebase()}>
<App />
</FirebaseContext.Provider>,
document.getElementById('root'),
);
serviceWorker.unregister();
// initializing the Firebase instance only once and using value prop to pass to context
src / components / App / index.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { withFirebase } from '../Firebase';
import Navigation from '../Navigation';
import LandingPage from '../Landing';
import SignInPage from '../SignIn';
import HomePage from '../Home';
import * as ROUTES from '../../constants/routes';
// route to components are implemented depending on route
// if there is a match in the prop then the component is displayed
class App extends Component {
constructor(props) {
super(props);
this.state = {
authUser: null,
};
}
componentDidMount() {
this.props.firebase.auth.onAuthStateChanged(authUser => {
authUser
? this.setState({ authUser })
: this.setState({ authUser: null });
});
}
render() {
return (
<Router>
<div>
<hr />
<Navigation authUser = {this.state.authUser} />
<hr />
...
</div>
</Router>
);
}
}
export default withFirebase(App);
src / components / Firebase / context.js:
import React from 'react';
const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
export default FirebaseContext;
src / components / Firebase / firebase.js:
import app from 'firebase/app';
import 'firebase/auth';
const firebaseConfig = {
...
};
class Firebase {
contructor() {
app.initializeApp(firebaseConfig);
this.auth = app.auth();
}
// *** Auth API ***
doSignInWithEmailAndPassword = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password);
doSignOut = () =>
this.auth.signOut();
}
export default Firebase;
src / components / Firebase / index.js:
import FirebaseContext, { withFirebase} from './context';
import Firebase from './firebase';
export default Firebase;
export { FirebaseContext , withFirebase };
我遇到的错误是"Cannot read property 'onAuthStateChanged' of undefined"
。由于我已经花费了数小时试图在线搜索信息,因此将不胜感激。谢谢!