【问题标题】:CRUD in React with Firestore for data in an arrayCRUD 在 React with Firestore 中用于数组中的数据
【发布时间】: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中创建的示例,以便更好地理解:

https://codesandbox.io/s/second-leeway-test-forked-ii0p6

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore backend


    【解决方案1】:

    您可以使用以下方法更新数组:

    firebase.firestore.FieldValue.arrayUnion(elem)
    firebase.firestore.FieldValue.arrayRemove(elem)
    

    见:https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

    要更新一个元素,您必须先将其从数组中移除,然后再添加修改后的元素。

    但是,我建议你通过子集合对数据库进行建模,以简化它们的管理,如下所示:

    - closets (collection)
        - unique ID (doc) 
                   - name (string)
                   - shorts (collection)
                           - short (doc)
                              - name (string)
                              - image (string)
    

    见:https://firebase.google.com/docs/firestore/data-model#subcollections

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多