我想将数据推送到Firebase数据库时生成密钥。我想用自己的功能来处理它们,
所以问题在于,当用户填写表单时,他会将数据发送到我们的实时数据库,其中包含一些图像(可选),而我不需要让该图像对象在DB中为空,因此如何处理该图像,以及当用户需要发送图像时,我想将此图像以相同顺序保存,而不是以“新顺序”保存。
节点
这是我的功能
handleOrder = () => {
const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
let file = imageOfPrblem.uri;
const path = "img_" + imageOfPrblem.fileName;
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({ // didn't updated the key generated just add new element with new key !!
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
}
handleImages = () => {
const options = {
title: "Select Images!",
storageOptions: {
skipBackup: true,
path: "images"
}
};
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.uri) {
this.setState({ imageOfPrblem: response });
}
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("ImagePicker Error: ", response.error);
} else if (response.customButton) {
console.log("User tapped custom button: ", response.customButton);
alert(response.customButton);
}
});
};
答案 0 :(得分:0)
来自任何Firebase快照ref
的推送ID位于ref.name()
中。
答案 1 :(得分:0)
这对我来说似乎很好:
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
console.log("new key: "+newChildRef.key);
ref.child(newChildRef.key).update({ secondChild: true });
运行此代码后,我将在新孩子的密钥中记录该JSON:
"-LdgLWu_wBNNicFlPDGj" : {
"firstChild" : true,
"secondChild" : true
}
实时演示:https://jsbin.com/hovoleh/edit?js,console
实时JSON:https://stackoverflow.firebaseio.com/55912103.json?print=pretty
更新:如果只想将现有数据和新数据都写入 new 位置:
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({
nameOfProblem: nameOfProblem,
description: description,
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
答案 2 :(得分:0)
我知道作者创建帖子已经有一段时间了,但也许有人会发现它很有用。
上面的答案有点错误,因为例如在:newChildRef
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
newChildRef <--- promise
ref = rdb.ref('name_of_your_ref');
var childRef = ref.push({
IdUser: currentUserId,
ProductCategory: pCategory,
ProductDescription: pDesc,
ProductId: pId,
ProductName: pName,
ProductPrice: pPrice,
ProductQuantity: pQuan
}).catch(err => console.log(err.message));
childRef.then(item => {
ref.child(item.key).update({
IdKey: item.key
}).then(() => history.push('/delivery/basket'));
});
你好,马修