首页 > 解决方案 > 不需要时的功能渲染

问题描述

sooooo 我一直在用 react 和 firebase 做一个学校项目。问题是我使用 firestore 数据创建 DOM 元素,但无论路径如何,它都会运行该函数,但我希望它仅在路径为“/journal”时运行,而不是在其他路径时运行。这是 app.js

import "./styles/base/App.css";
import "./styles/pages/index.css";
import Nav from "./pages/nav";
import Journal from "./pages/journal";
import Authors from "./pages/authors";
import CreateArticle from "./pages/articles/create";
import ArticlesDetails from "./pages/articles/articles pages/articlesdetails";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
  return (
    <Router>
      <div className="App">
        <Nav />
        <Switch>
          <Route path="/" exact component={Index} />
          <Route path="/journal" exact component={Journal} />
          <Route path="/articles/create" exact component={CreateArticle} />
          <Route path="/articles/:id" exact component={ArticlesDetails} />
          <Route path="/authors" exact component={Authors} />
        </Switch>
      </div>
    </Router>
  );
}

这就是路径为“/journal”时呈现的内容

import "../styles/base/App.css";
import "../styles/pages/journal/Journal.css";
import firebase from "../firebase";
const db = firebase.firestore();

db.collection("articles")
  .limit(4)
  .get()
  .then((snapshot) => {
    snapshot.docs.forEach((doc) => {
      renderArticle(doc);
    });
  });
const articlelist = document.querySelector("#articles");
//create element and render in article page
function renderArticle(doc) {
  let listitem = document.createElement("li");
  let title = document.createElement("h3");
  let author = document.createElement("h6");

  listitem.setAttribute("data-id", doc.id);
  author.textContent = "Wrote by - " + doc.data().author;
  title.textContent = doc.data().title;

  listitem.appendChild(title);
  listitem.appendChild(author);

  articlelist.appendChild(listitem);
} 

function Journal() {
  return (
    <div className="journalbody">
      <header className="journal-header">
        <div className="journal-title">
          <h1>Our Journal</h1>
          <h6>Surf into articles wrote by our students !</h6>
        </div>
      </header>

      <div className="recent" id="recent">
        <div className="recent-content">
          <h3>Recent Article</h3>
          <a href="#">
            See All articles
          </a>
          <ul id="articles"></ul>
        </div>
      </div>
 
      
  );
}
export default Journal;

唯一的问题是当路径不是“/journal”时它会运行函数“renderArticle”,所以它会弄乱其他页面

很抱歉文字和拼写错误的负载,如果您有解决方案,请提前感谢您

标签: javascriptreactjsfirebase

解决方案


您可以直接在 JSX 中使用 for 循环(通过文档)。

只需获取您的数据,将其添加到您的状态,然后在 JSX 中使用它。见下文

不太确定为什么下面的代码会返回错误(我第一次尝试在这里使用 React 钩子)但您可以在此处查看代码 ->沙箱

function App() {
  const [snapshotDocsState, setSnapShot] = React.useState([]);
   React.useEffect(() => {
    // const snapshot = await db.collection("articles").limit(4).get()
    const snapshot = {
      docs: [
        {
          id: 1,
          author: "First Author",
          title: "Doc 1"
        },
        {
          id: 2,
          author: "Second Author",
          title: "Doc 2"
        },
        {
          id: 3,
          author: "Third Author",
          title: "Doc 3"
        }
      ]
      }
    setSnapShot(snapshot.docs);
  }, []);

  return (
    <div>
      <ul id="articles">
        {snapshotDocsState.map((doc, index) => (
          <li key={doc.id} data-id={doc.id}>
            <h3>{doc.title}</h3>
            <h6>{doc.author}</h6>
          </li>
        ))}
      </ul>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


推荐阅读