我正在构建一个电子商务应用程序,我试图将用户按下的每个项目添加到购物车中(调用functionsCombined())保存在Firebase中,但我不想在记录中重复
this.state = {
added: false,
duplicate: false,
}
componentWillMount() {
//gets the data in firebase
this.props.fetchData();
}
functionsCombined(recipe) {
//the user pressed add to cart
//recipe is the item to be added
if (this.state.added) {
} else {
this.functionZero(recipe);
this.functionOne();
this.functionTwo(recipe);
}
}
functionZero(recipe) {
//this.props.check is the data we pulled from firebase
//to check if the firebase records is the same as the one here
/but even when that's true, setState doesn't work for some reason
this.props.check.map((one) => {
if (one.id === recipe.id) {
this.setState({
duplicate: true
})
} else {
}
})
}
functionOne() {
this.setState({
added: true
})
}
functionTwo(recipe) {
if (this.state.duplicate === false) {
const {
currentUser
} = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/recipes`)
.push(recipe);
} else {
}
}
答案 0 :(得分:0)
在保存到Firebase之前,可以使用通用唯一标识符(UUID)。 像这样
const uuidv4 = require('uuid / v4');
.....
firebase.database().ref(`/users/${currentUser.uid}/recipes`+uuidv4())
.push(recipe);
.....
这将为您保存的每个Firebase记录生成唯一的ID