【发布时间】:2020-10-26 18:51:51
【问题描述】:
太好了,我一直在用 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”,所以它会弄乱其他页面
对大量文字和拼写错误感到抱歉,如果您有解决方案,请提前感谢您
【问题讨论】:
-
它运行它是因为
renderArticle在文件的导出函数Journal之外。将它添加到函数中,我想它会好的。/journal路径呈现Journal组件,它是从您的文件中导出的function Journal。renderArticle在外面 -
also.. 也许你应该使用 react / jsx 来渲染元素而不是使用 dom api
-
问题是我对 react 是全新的,我只是在重新制作一个我用 html 制作的网站,所以我仍然不知道如何使用 react jsx ......当我将 renderArticle 放在 Journal 中,只有当我在重新加载页面后保存代码时才会呈现它,它说 articlelist 为空....
标签: javascript reactjs firebase