我具有以下代码,用于将用户数据从Firebase导入到我的React应用程序中:
import React from 'react';
import AuthUserContext from './AuthUserContext';
import withAuthorization from './withAuthorization';
import * as firebase from 'firebase';
import { config, database, db, auth, itembase, } from
'../firebase/firebase';
class Collection extends React.Component {
constructor (props) {
super(props)
this.state = {
collection: []
};
}
//Data from Firebase Database
componentDidMount() {
var userUid = firebase.auth().currentUser.uid;
const collection = firebase.database().ref(`/users/${userUid}/collection/`)
collection.on('value', snapshot => {
this.setState({
collection: snapshot.val(),
})
})
}
//Remove from user collection
removeToCollection(key, e) {
const userUid = firebase.auth().currentUser.uid;
const item = {
nom: this.state.collection[key].nom,
parution: this.state.collection[key].parution
};
firebase.database().ref(`users/${userUid}/collection/`).remove(item)
}
render(){
const collection= Object.keys(this.state.collection).map(key => {
return (
<div key={key}>
<h3>{this.state.collection[key].nom}</h3>
<p>{this.state.collection[key].parution}</p>
<button className="btn btn-danger" onClick={this.removeToCollection.bind(this, key)}>Remove</button> </div>
)
});
return (
<div>
{collection}
</div>
)
}
}
const authCondition = (authUser) => !!authUser;
export default withAuthorization(authCondition)(Collection);
就像您看到的那样,当用户单击“删除”按钮时,我具有删除数据的功能。 我的问题是,当我单击按钮时,出现一条错误消息
这是我的数据库的样子:
非常感谢您的帮助!
答案 0 :(得分:1)
错误来自:
firebase.database().ref(`users/${userUid}/collection/`).remove(item)
您似乎正在尝试传递要删除的项目。 remove
方法不是这样的。
remove
方法将删除您调用它的位置上的所有数据。如果您将参数传递给remove
,则Firebase希望该参数是在删除完成(或失败)之后调用的回调函数。
因此,您需要创建要删除的商品的完整路径:
let key = "-LlouZxkW1N3Llt6h5nm"
firebase.database().ref(`users/${userUid}/collection/${key}`).remove()
如果您不知道要删除的项目的密钥,则首先需要执行查询以找到该项目并确定其密钥。