我正在尝试将数据保存在Firebase实时数据库中,但是当我运行该页面并尝试提交我的输入时,将显示错误消息“ TypeError:无法读取未定义的属性'state'”。 enter image description here。我不知道我是否在this.state中正确执行了操作。我有个获取值的想法,但是我不知道如何处理这些值并传递给其他人。
class SideNav extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
fullname: '',
purok: '',
userType: 'purokLeader'
}
}
state = {
open: false,
};
onOpenModal = () => {
this.setState({ open: true });
};
onCloseModal = () => {
this.setState({ open: false });
};
signOut() {
firebaseApp.auth().signOut();
};
signsUp() {
firebaseApp.database().ref('Usersyeah/').push({
name: this.state.fullname,
purok: this.state.purok,
email: this.state.email,
password: this.state.password,
user: "purokLeader"
});
};
render() {
const { open } = this.state;
return (
<div className="container">
<div className="sidebar" style={sideBarColor}>
<div className="logoCont">
<img src={logo} className="sideLogo"/>
</div>
<Link to="/" ><img src={home} style={{width: '30px'}} alt="Log Out image" /> Dashboard</Link>
<Link to="/docproc"> Document Services</Link>
<Link to="/sumbong"> Sumbong Center</Link>
<Link to="/announce"> Announcement</Link>
<div style={{ marginTop: ''}} ><Link to="#" onClick={() => this.onOpenModal()}><img src={logoutIcon} style={{width: '30px'}} alt="Log Out image" /> Add User</Link></div>
<div style={{ marginTop: '35px'}} ><Link to="#" onClick={() => this.signOut()}><img src={logoutIcon} style={{width: '30px'}} alt="Log Out image" /> Log out</Link></div>
</div>
<div>
<Modal open={open} onClose={this.onCloseModal} >
<h4>Simple centered modal</h4>
<input name="Name" id="fullname" type="text" ref="Fname" placeholder="Enter Your Fullname..." style={mainDivInput} onChange={event => this.setState({ fullname: event.target.value })}/>
<input id="PurokNum" type="text" ref="PurokNum" placeholder="Purok No." style={mainDivInput} onChange={event => this.setState({ purok: event.target.value })}/>
<input id="email" type="email" ref="Email" placeholder="Enter Your Email..." style={mainDivInput} onChange={event => this.setState({ email: event.target.value })}/>
<input name="password" id="password" type="password" ref="Pword" placeholder="Enter Your Password..." style={mainDivInput} onChange={event => this.setState({password: event.target.value })} />
<div>
<button className="btn btn-primary" style={{height: '40px', marginTop: '100px', marginLeft: '330px'}} onClick={this.signsUp} >Create</button>
</div>
</Modal>
</div>
</div>
);
}
}
export default withRouter(SideNav) ;
答案 0 :(得分:1)
这是由于this
引起的,请通过箭头功能更改signsUp()
功能
signsUp = () => {
firebaseApp.database().ref('Usersyeah/').push({
name: this.state.fullname,
purok: this.state.purok,
email: this.state.email,
password: this.state.password,
user: "purokLeader"
});
};
答案 1 :(得分:1)
如Praveen所述,使用箭头函数或在构造函数中手动绑定该函数
您需要手动绑定该函数或将Turing绑定到箭头函数以访问该函数内的状态或道具
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
fullname: '',
purok: '',
userType: 'purokLeader'
}
this.signsUp = this.signsUp.bind(this);
}