Javascript 如何在React Js中添加Firebase Firestore文档自动生成的ID外接程序集合自定义数据字段
我想在我的项目中使用这个例子。参见示例 但是当我用react js实现这个示例时,我不能这样做。请参阅我的代码:Javascript 如何在React Js中添加Firebase Firestore文档自动生成的ID外接程序集合自定义数据字段,javascript,reactjs,firebase,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Firestore,我想在我的项目中使用这个例子。参见示例 但是当我用react js实现这个示例时,我不能这样做。请参阅我的代码: constructor(props) { super(props); this.ref = firebase.firestore().collection('stack_over') const id = firebase.firestore().collection('stack_over').doc().id this.state = {
constructor(props) {
super(props);
this.ref = firebase.firestore().collection('stack_over')
const id = firebase.firestore().collection('stack_over').doc().id
this.state = {
question_id: id,
question_title: '',
};
}
onSubmitData = (e) => {
e.preventDefault()
const { question_id, question_title } = this.state;
this.ref.add({ question_id, question_title })
.then((docRef) => {
this.setState({ question_id:'', question_title:'' }) }).catch((error) => { console.error("", error) }) }
我希望在插入新数据时执行此操作,然后插入自动生成的文档id问题\u id字段。我该怎么做呢?这个:
const id = firebase.firestore().collection('stack_over').doc().id
将为您提供一个自动生成的id,但如果要向数据库添加数据,则需要使用set()
:
onSubmitData=(e)=>{e.preventDefault()const{question\u id,question\u title}=this.state;this.ref.add({question\u id,question\u title})。然后((docRef)=>{this.setState({question\u id:'',question\u title:'}).catch((错误)=>{console.error(“,error)}
firebase.firestore().collection('stack_over').doc(id).set({
question_id: id,
question_title: 'title',
}).then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});