【发布时间】:2021-11-15 15:27:44
【问题描述】:
这是我第一次使用 Firebase 作为我的后端,我可以成功访问和获取我的 React 应用程序中的数据,但是我在 CRUD 操作方面遇到了问题。
我的收藏示例:
- closets (collection)
- unique ID (specific user)
- name (string)
- shorts (array of objects - map)
- 0 (first object in array)
- name (string)
- image (string)
.........
.........
我可以读取所有文件,但无法更新或删除它们。我需要访问数组中的所有数据(例如基于上述示例的 shorts 数组)并且能够更改名称或remove the whole object。
使用自定义钩子映射数据:
export const useGetData = () => {
const [documents, setDocuments] = React.useState([]);
const db = firebase.firestore();
React.useEffect(() => {
db.collection("closets")
.get()
.then((querySnapshot) => {
let arr = [];
querySnapshot.docs.map((doc) =>
arr.push({ id: doc.id, name: doc.data() })
);
setDocuments(arr);
});
}, [db]);
return [documents];
};
这里我正在尝试在dress array 中更新name
const [nameValue, setNameValue] = React.useState("");
const db = firebase.firestore();
const getNameValue = (event) => {
setNameValue(event.target.value);
};
const updateValue = () => {
db.collection("closets")
.doc(doc)
.update({
"dress.name": nameValue
})
.then(function () {
console.log("Document successfully updated!");
})
.catch(function (error) {
console.error("Error updating document: ", error);
});
};
return (
<>
<input onBlur={getNameValue} type="text" />
<button onClick={updateValue}>Update</button>
</>
得到错误 s.indexOf 不是函数
我不确定如何更新对象中的这个特定字符串,它是数组的一部分。
这里是在codesandbox中创建的示例,以便更好地理解:
【问题讨论】:
标签: javascript reactjs firebase google-cloud-firestore backend