简体   繁体   English

如何在 firebase firestore 的数组中添加 map 以做出反应?

[英]How to add a map in array in firebase firestore in react?

  addMoreCases = (e) => {
    e.preventDefault();
    this.setState({
      makeActive10: false,
      toggleDetails10: true,
    });
    const studentName = this.props.location.state.selectedStudent.basicData
      .studentName;
    var db = fire.firestore();
    const casesObject = this.state.casesObject;
    db.collection("students")
      .where("basicData.studentName", "==", studentName)
      .get()
      .then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
          console.log(doc.id, " => ", doc.data());
          db.collection("students")
            .doc(doc.id)
            // .doc(  )
            .update(
              {
                ...{
                  casesAndAssociatesData: {
                    ...{ casesObject },
                  },
                },
              }

              // { merge: true }
            );
        });
      });
    this.setState({
      casesObject: [
        // { ...initialCasesForm }
        {
          casesPoliceStation: "",
          crimeNumber: "",
          sectionOfLaw: "",
          stage: "",
        },
      ],
    });
  };
                        <Form onSubmit={this.addMoreCases}>
                          <Form.Row key={index}>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="casesPoliceStation"
                                placeholder="Police Station"
                                value={cases.casesPoliceStation}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="crimeNumber"
                                placeholder="Crime Number"
                                value={cases.crimeNumber}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="sectionOfLaw"
                                placeholder="Section Of Law"
                                value={cases.sectionOfLaw}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Form.Control
                                style={{ marginBottom: 20 }}
                                type="text"
                                onChange={(e) =>
                                  this.casesObjectUpdate(e, index)
                                }
                                name="stage"
                                placeholder="Stage"
                                value={cases.stage}
                                onKeyPress={(e) => {
                                  e.key === "Enter" &&
                                    e.preventDefault();
                                }}
                              />
                            </Col>
                            <Col>
                              <Button
                                type="submit"
                                variant="outline-primary"
                              >

Here, in the above code I'm trying to add some more maps in an array using for the specific document ID.在这里,在上面的代码中,我尝试在数组中添加更多地图,用于特定的文档 ID。 So that on button submit, I'm alling function "addMoreCases".所以在按钮提交时,我会说 function “addMoreCases”。 And it sould add another map within casesObject array, within casesAndAssociatesData field.并且它应该在 caseObject 数组、casesAndAssociatesData 字段中添加另一个 map。 I'll be attaching my firestore database image, and in that, within "casesAndAssociatesData" field, within "casesObject" array, I need another map with the form values should be added with the incremented Index in the above image, if I enter the values in form and hit submit button, I need the values to be added in "casesObject" array with index "2" in "casasAndAssociatesData"我将附上我的firestore数据库图像,在“casesAndAssociatesData”字段中,在“casesObject”数组中,我需要另一个map ,如果我输入上面图像中的递增索引,则应该添加表单值表单中的值并点击提交按钮,我需要将值添加到“casasAndAssociatesData”中索引为“2”的“casesObject”数组中

这是我的数据库结构 As far as I understand you have the following structure in your database:据我了解,您的数据库中有以下结构:

collection:
 document:
    casesAndAssociatesData:obj_array
    casesObject:obj_array

And you would like to add more data to the casesObject .并且您想向casesObject添加更多数据。 Since casesObject is a filed of the document, you will have to update it every time you add more data.由于casesObject是文档的一个字段,因此每次添加更多数据时都必须更新它。

So the approach would be:所以方法是:

  1. Get all the data from the loaded document as an map array.从加载的文档中获取所有数据作为 map 数组。
  2. Add another element to that array.向该数组添加另一个元素。
  3. Update the entire casesObject field with the new data.使用新数据更新整个casesObject字段。

This is an example of how you should modify your code:这是一个如何修改代码的示例:

querySnapshot.forEach(function (doc) {

   console.log(doc.id, " => ", doc.data());

   //Prepare the new data that you want to add :
   var newCasesObject = {
       casesPoliceStation: "New police station Value",
       crimeNumber: "New crime value",
       sectionOfLaw: "New section of law",
       stage: "ss",
   }

   //Get the array with data from the loaded document
   var dataObj = doc.data().casesObject;

   //Push the new data to that array
   dataObj.push(newCasesObject);

   //Call another function that will update the document with the new data
   updateData(doc.id, dataObj);

});

//The new update function:
async function updateData(docID, obj){

   const cityRef = db.collection('[COLLECTION_NAME]').doc(docID);

   // Set the 'capital' field of the city
   const res = await cityRef.update({casesObject: obj});

}

I have tested this on my database and it is working as you described.我已经在我的数据库上对此进行了测试,它的工作方式与您描述的一样。 It updates only the field casesObject while every time adding a new map data.它只更新字段casesObject ,而每次添加新的 map 数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM