将构造函数与props一起使用的正确方法?

问题描述 投票:0回答:1

当我打印到控制台时,它说未加载auth,因此没有auth.uid。为什么?

    constructor(props) {
        super(props);
        this.state = {
            auth : props,
            links : props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        };   
    }

...

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);

reactjs firebase-authentication react-props
1个回答
0
投票

也许最好在构造函数之外定义状态:

// Inside your component but not inside the constructor:

state = {
  auth : this.props.auth,
  links : this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
};   

但是即使如此,您只是将redux状态props插入到组件状态。为什么?为什么不像这样直接从redux状态直接读取?

class MyComponent extends React.Component{

  render(){
    return this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
  }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);
© www.soinside.com 2019 - 2024. All rights reserved.