问题:
我想使用React和Firebase开发一个项目。但是当按钮被反应按下时,有时会被添加。有时该按钮不起作用。这是什么原因呢?我认为这是编码错误,但我不知道错误是什么。
App.js
import React, { Component } from 'react'
import db from '../Firebase';
const INITIAL_STATE = {
username: '',
email: '',
password: ''
};
export class index extends Component {
constructor(props){
super(props);
this.state = {...INITIAL_STATE};
}
onSubmit = () => {
const{ username, password, email} = this.state;
db.collection('users').add({
'username': username,
'password': password,
'email': email
})
.then(function(docRef) {
console.log("Document written with ID: ", username);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
onChange = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
const{ username, password, email} = this.state;
return (
<div>
<h2>sign up</h2>
<div className='container'>
<form onSubmit={this.onSubmit}>
<input type='text'
className='form-control mt-2'
placeholder='username'
name='username'
onChange={this.onChange}
value={username}
/>
<input type='email'
className='form-control mt-2'
placeholder='email'
name='email'
onChange={this.onChange}
value={email}
/>
<input type='text'
className='form-control mt-2'
placeholder='password'
name='password'
onChange={this.onChange}
value={password}
/>
<button type='submit'
className='btn btn-dark bg-dark btn-block mt-4'
>SIGN UP
</button>
</form>
</div>
</div>
)
}
}
export default index;
Firebase / index.js
import firebase from '@firebase/app';
import 'firebase/firestore';
firebase.initializeApp({
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***"
})
var db = firebase.firestore();
export default db;
代码如上所示。页面上有“用户名”,“密码”和“电子邮件”字段。每次更改时,功能“ onChange”都会起作用并更新“ state”字段。按下按钮后,它将信息发送到“ firebase”数据库(这正是问题所在。它没有在数据库中发送。)
答案 0 :(得分:0)
您的状态实现有点错误。 尝试在提交功能中控制状态, fire base函数会产生任何错误吗?
答案 1 :(得分:0)
您不应该在event.preventDefault()
处理程序中调用onSubmit
吗?像这样写:
onSubmit = (event) => {
event.preventDefault();
// your existing code here....
}