【问题标题】:React :Unable to get this.state.name inside the component反应:无法在组件内获取 this.state.name
【发布时间】:2019-09-25 05:27:27
【问题描述】:

我是 react js 的新手,我正在尝试在我的 react js 应用程序中获得 firebase 身份验证。我想要做的是,如果用户已登录,那么它应该在我的返回页面中返回经过身份验证的用户的姓名或电子邮件 ID。我一直在尝试在该州实施各种选择,但我无法得到它。 这是我的代码

class Signin extends React.Component {
    state = {
        email :'',
        password:'',
        name :'',
        authUser:'',
    }
    getDetails = (e) => {
        firebase.auth().onAuthStateChanged(authUser => {
          authUser
            ? this.setState({ authUser }) 
            : this.setState({ authUser: null });
        });
    }
    render() {
        const {
            user,
            signInWithGoogle,
        } = this.props;

        return (
            <div>
            {
                user
                    ? (
                        <div>
                            <button className="btn blue lighten-2 z-depth-0" onClick={this.logOut}>Sign out</button>
                            <button className="btn dark lighten-4 z-depth-0" onClick={this.getDetails}>GetDetails</button>
                            <input type = "text" className="dark lighten-2 z-depth-0" >
                                {this.state.authUser ? this.state.authUser :this.state.name}
                            </input>
                        </div>
                    )
                    : (
                        <button className="btn blue lighten-2 z-depth-0" onClick={signInWithGoogle}>Sign in with Google</button>
                    )
            }
            </div>
        )
    }
}

const firebaseAppAuth = firebaseApp.auth();
const loginAuth = firebaseApp.auth().signInWithEmailAndPassword;
const providers = {
    googleProvider: new firebase.auth.GoogleAuthProvider(),
};

export default withFirebaseAuth({
    providers,
    firebaseAppAuth,
    loginAuth,
})(Signin);

在此页面中,我可以通过firebase 登录用户,但无法获取onAuthstateChanged。 我错过了什么吗?还是我应该在登录后存储任何变量?

【问题讨论】:

  • 您是否在任何地方设置了name 的值?
  • 我没有为它设置值。但是我在状态中提到了它。

标签: javascript reactjs react-native react-router


【解决方案1】:

在您分享的这部分代码中,authUser 字段设置为组件状态:

firebase.auth().onAuthStateChanged(authUser => {
          authUser
            ? this.setState({ authUser }) 
            : this.setState({ authUser: null });
        });

但没有必要这样做。

withFirebaseAuth 高阶组件负责对用户进行身份验证,已经将 does that when it mountsforwards a user prop 传递给它所包装的组件。

<input type = "text" className="dark lighten-2 z-depth-0" >
   {user && user.displayName}
</input>

【讨论】:

  • 感谢您的宝贵帮助。接下来,我想在另一个文件中提到的另一个组件中使用authUser 状态。我可以这样做还是应该在那个文件中也需要onAuthStateChanged
  • 使用withFirebaseAuth HOC 封装需要认证的组件,并使用转发给封装组件的user prop
猜你喜欢
  • 2019-04-24
  • 2020-03-21
  • 2021-05-03
  • 1970-01-01
  • 2023-02-11
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
相关资源
最近更新 更多