【问题标题】:Bootstrap-table displays both "No matching records found" and Records in bootstrap-table with Firebase realtime databaseBootstrap-table 使用 Firebase 实时数据库显示“No matching records found”和 bootstrap-table 中的记录
【发布时间】:2021-07-30 10:55:01
【问题描述】:

我正在使用 bootstrap-table 并尝试显示一个包含来自 firebase 实时数据库的数据的表。

数据库的内容正确呈现,但是我在我的表中看到“未找到匹配的记录”消息。

使用搜索和排序功能还可以完全清除表格,并且需要刷新才能恢复数据。

import React, { useState, useEffect } from "react";
import firebaseDb from "../firebase";

const StarTrekTable = () => {
  var [contactObjects, setObjects] = useState({});

  useEffect(() => {
    firebaseDb.child("unwatched").on("value", (snapshot) => {
      if (snapshot.val() != null)
        setObjects({
          ...snapshot.val(),
        });
    });
  }, []);

  return (
    <>
      <div class="jumbotron jumbotron-fluid">
        <div class="container">
          <h1 class="display -4 text-center">Star trek series</h1>
        </div>
      </div>
      <div>
        <div className="col-md-12">
          <table data-toggle="table" data-pagination="true" data-search="true">
            <thead className="thread-light">
              <tr>
                <th>Title</th>
                <th>Series</th>
                <th>Season</th>
                <th>Episode</th>
                <th>Stardate</th>
                <th>Air Date</th>
              </tr>
            </thead>
            <tbody>
              {Object.keys(contactObjects).map((id) => {
                return (
                  <tr>
                    <td>{contactObjects[id].title}</td>
                    <td>{contactObjects[id].series}</td>
                    <td>{contactObjects[id].season}</td>
                    <td>{contactObjects[id].episode}</td>
                    <td>{contactObjects[id].stardate}</td>
                    <td>{contactObjects[id].airdate}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

export default StarTrekTable;

非常感谢任何帮助。

Table shows both records as expected and "No matching records found"

Image of my Firebase realtime database setup

【问题讨论】:

    标签: reactjs firebase firebase-realtime-database bootstrap-4 bootstrap-table


    【解决方案1】:

    在您的组件第一次渲染时,您的contactsObject{},这导致&lt;tbody&gt; 在第一次渲染时为空。在代码的其他地方,可能在引导程序的某个地方,“未找到匹配的记录”被添加到源代码中。一旦您的听众找到未观看的剧集,下载、解析并将它们添加到 &lt;tbody&gt; 反应中,然后删除它添加的条目(无),然后插入新条目。因为“没有找到匹配的记录”是在 React 之外添加的,所以它不知道它在那里并且没有被删除。不要让任何其他代码添加此行,而是在您仍在加载数据或表为空时自行定义。

    如果你还没有使用 react-bootstrap,你应该使用它,这样与 Bootstrap 捆绑的原始 JavaScript 就不会像你在这里看到的那样与 React 争夺控制权。

    注意:在 React 中渲染数据数组时,请确保为每个条目指定 key,以便 React 可以在新渲染时有效地操作条目。

    清理一些其他的东西,这给出了:

    import React, { useState, useEffect } from "react";
    import firebaseDb from "../firebase";
    
    const StarTrekTable = () => {
      // - renamed variables to reflect content
      // - used array instead of object
      // - used const instead of var
      const [episodeData, setEpisodeData] = useState([]);
      const [episodesLoaded, setEpisodesLoaded] = useState(false);
    
      useEffect(() => {
        // store Reference for attaching and detaching listeners
        const unwatchedRef = firebaseDb.child("unwatched");
      
        // because you use a `.on` listener, don't forget to store
        // the listener so we can detach it
        const listener = unwatchedRef
          .on("value", (snapshot) => {
            if (!snapshot.exists()) {
              // no data to show and/or unwatched is empty
              // update state variables
              setEpisodeData([]);
              setEpisodesLoaded(true);
              return;
            }
            
            // Use forEach to maintain the order of the query, using `...snapshot.val()`
            // for the whole result will often lead to unexpected results.
            const freshEpisodeData = [];
            snapshot.forEach((childSnapshot) => {
              freshEpisodeData.push({ ...childSnapshot.val(), key: childSnapshot.key });
            });
    
            // update state variables
            setEpisodeData(freshEpisodeData);
            setEpisodesLoaded(true);
          });
          
        // when component is detached, remove the listener
        return () => unwatchedRef.off("value", listener);
      }, []);
    
      return (
        <>
          <div class="jumbotron jumbotron-fluid">
            <div class="container">
              <h1 class="display -4 text-center">Star trek series</h1>
            </div>
          </div>
          <div>
            <div className="col-md-12">
              <table data-toggle="table" data-pagination="true" data-search="true">
                <thead className="thread-light">
                  <tr>
                    <th>Title</th>
                    <th>Series</th>
                    <th>Season</th>
                    <th>Episode</th>
                    <th>Stardate</th>
                    <th>Air Date</th>
                  </tr>
                </thead>
                <tbody>
                  { !episodesLoaded
                    ? (
                      <tr key="data-loading">
                        <td colspan="6"><i>Loading...</i></td>
                      </tr>
                    )
                    : (episodeData.length === 0
                      ? (
                        <tr key="data-empty">
                          <td colspan="6">No unwatched episodes available. You're all caught up!</td>
                        </tr>
                      )
                      : episodeData.map(({ key, title, series, season, episode, stardate, airdate }) => (
                        <tr key={key}>
                          <td>{title}</td>
                          <td>{series}</td>
                          <td>{season}</td>
                          <td>{episode}</td>
                          <td>{stardate}</td>
                          <td>{airdate}</td>
                        </tr>
                      )))
                  }
                </tbody>
              </table>
            </div>
          </div>
        </>
      );
    };
    
    export default StarTrekTable;
    

    注意:对于不太可能更改的静态数组,您的数据库结构很好,但我强烈建议您不要对数据使用数字键(02 等。 ) 而是使用其他东西,例如(S01E01-02S01E03 等)或 Firebase 推送 ID。考虑这个(但仍然有效)blog post 进行推理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2016-11-01
      • 2017-08-08
      • 2017-12-01
      • 2020-05-28
      • 1970-01-01
      • 2015-12-06
      相关资源
      最近更新 更多