身份验证期间如何更改this.state状态? Firebase + React-Router

时间:2019-01-06 23:48:17

标签: javascript reactjs firebase react-router firebase-authentication

我使用react-router和Firebase进行身份验证。对于此功能,文件 SignIn 中的 onButtonClick 必须将 App.js 中的状态更改为true。这该怎么做?也许除了我的主意之外还有其他方法吗?

App.js:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
 ....
import firebase from './firebase/firebase.js';

class App extends Component {

state = {
      signedInStatus : false
};

render(){
  const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props) => (
        this.state.signedInStatus
        ? <Component {...props} />
        : <Redirect to='/signIn' />
    )} />
  )
  return(
    <div>
      <Header signedInStatus={this.state.signedInStatus} />
    <Router>
    <Switch>
        <Route exact path="/" component={SignIn}/>
        <Route path="/signIn" component={SignIn}/>
        <Route path="/register" component={Register} />
        <PrivateRoute path="/home" component={Home} />
    </Switch>
    </Router>
      </div>
    );
  }
}

export default App;

第二个文件可确保使用输入信息来到达用户机柜。 SignIn.js:

    import...
    class SignIn extends Component {
    state = {
          email: '',
          password: '',
    };

    onButtonClick = (event) =>{
      event.preventDefault();
      firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
           .then((user) => {
             this.props.history.push('/home')
             console.log("ok")  /// here i want add something to change 
           })                   /// this.state.signedIn for true in App
           .catch((error) => {
            console.log(error);
            alert(error);
          });
    }

    onChangeInputEmail = (event) => {
      this.setState({email: event.target.value})
    };

    onChangeInputPassword = (event) => {
      this.setState({password: event.target.value})
    };

    render(){
      return (
            ...
      )
    };

    export default withRouter(SignIn);

1 个答案:

答案 0 :(得分:0)

您需要定义一种方法来更新App.js的状态,然后可以将props传递给组件,如下所示

<Route
  path='/signIn'
  render={(props) => <SignIn {...props} changeSignedInStatus={this.changeSignedInStatus} />}
/>