【问题标题】:Loading data from Firebase real time database to React hook component将数据从 Firebase 实时数据库加载到 React 钩子组件
【发布时间】:2021-08-31 15:10:56
【问题描述】:

我是 Firebase 实时数据库的新手,我发现一些 React 挂钩代码与 Firestore 不同。话虽如此,我尝试制作一个功能组件以放入主应用程序。我正在尝试匹配代码中的值,但我还没有弄清楚。

import React, { useState, useEffect } from "react";
import firebase from "firebase";
import {
  Row,
  Col,
  Button,
  CardTitle,

} from "reactstrap";

const Configs = () => {
    const [userData, setUserData] = useState("");
  
    const getUser = () => {
      const cdb = firebase.database().ref("/pos").child("/pos1")
      let userlist = [];
      cdb.on("value", (snapshot) => {
          userlist.forEach(snapshot=> {
            userlist.push(snapshot.val());
          });
          console.log(JSON.stringify(snapshot, null, 2));
          setUserData(userlist);
      }
      )
    
    };
  
    useEffect(() => {
      getUser();
    }, []);
  
    const handleUpdate = () => {
      firebase.database()
      .ref("/pos")
      .child("/post1")
      .update({
        pos1_a: userData.pos1_a,
        pos1_b: userData.pos1_b,
        pos1_c: userData.pos1_c,
      })
      .then(()=> {
        console.log('Pos Updated')
      })
    };
    return (
        <React.Fragment>
          <div className="page-content">
            <Row>
              <Col>

                    <CardTitle className="h4">Main Configurations</CardTitle>
                    <p className="card-title-desc">
                      Settings will be written on<code> database</code> applied to
                      the webhook loads <code>&lt;input&gt;</code> <code>type</code>
                      .
                    </p>
    
                    <Row className="mb-3">
                      <label
                        htmlFor="example-text-input"
                        className="col-md-2 col-form-label"
                      >
                        userData_A
                      </label>
                      <div className="col-md-10">
                        <div>
                          <input
                            className="form-control"
                            type="number"
                            min="0"
                            value={userData ? userData.pos1_a : ""}
                            onChange={(txt) =>
                              setUserData({
                                ...userData,
                                pos1_a: txt,
                              })
                            }
                          />
                        </div>
                      </div>
                    </Row>
                    <Row className="mb-3">
                      <label
                        htmlFor="example-search-input"
                        className="col-md-2 col-form-label"
                      >
                        userData_B
                      </label>
                      <div className="col-md-10">
                        <div>
                          <input
                            className="form-control"
                            type="number"
                            min="0"
                            value={userData ? userData.pos1_b : ""}
                            onChange={(txt) =>
                              setUserData({
                                ...userData,
                                pos1_b: txt,
                              })
                            }
                          />
                        </div>
                      </div>
                    </Row>
                    <Row className="mb-3">
                      <label
                        htmlFor="example-search-input"
                        className="col-md-2 col-form-label"
                      >
                        userData_C
                      </label>
                      <div className="col-md-10">
                        <div>
                          <input
                            className="form-control"
                            type="number"
                            min="0"
                            value={userData ? userData.pos1_b : ""}
                            onChange={(txt) =>
                              setUserData({
                                ...userData,
                                pos1_b: txt,
                              })
                            }
                          />
                        </div>
                      </div>
                    </Row>
                    
                    <Button
                    buttonTitle="Update"
                    color="primary"
                    type="submit"
                    onPress={handleUpdate}
                  >
                    Submit change
                  </Button>
              </Col>
            </Row>
          </div>
        </React.Fragment>
      );
    };
    
    export default Configs;

    ```

console.log 以 JSON 格式获取数据,所以我认为它是对象形式的。 对我来说,练习的重点是让表单更新与实时数据库同步。我该怎么做?

【问题讨论】:

    标签: reactjs firebase-realtime-database react-hook-form


    【解决方案1】:

    我们没有您的数据库结构,但基本上您有两种可能的解决方案:

    1. 您的数据保存为列表:
    const tempList = [];
    
    userlist.forEach((snapshot) => {
      tempList.push(snapshot.val());
    });
    
    setUserData(tempList);
    

    你在这里使用相同的变量userlist

    1. 您的数据是一个对象:
    const tempList = [];
    
    userlist.forEach((snapshot) => {
      Object.entries(snapshot.val()).forEach(([key, value]) => {
        tempList.push(value);
      });
    });
    
    setUserData(tempList);
    
    

    【讨论】:

    • 我的错。 JSON 非常简单 { "post1": { "pos1_a" : "1", "pos1_b" : "abc", "pos1_c" : "test" } } 我试图将数据映射到一个对象上并将它们全部保存在一起。
    • 那么第二个代码应该适合你。
    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2021-10-04
    • 2019-04-25
    相关资源
    最近更新 更多