未为 document.querySelector 定义文档



我正在尝试将数据从我的火碱后端渲染到我的网站上。我在../组件/店面.js

function Storefront(props) {
return (
<section>
<ul className="service-list"></ul>
</section>
}

在另一个文件中,../pages/storefront.js,我正在尝试将函数呈现为"服务列表",

import Storefront from './../components/Storefront';
const servicelist = document.querySelector('.service-list');
function renderServices(doc){
let li = document.createElement('li');
let name = document.createElement('span');
let description = document.createElement('span');
li.setAttribute('data-id', doc.id);
name.textContent = doc.data().name;
description.textContent = doc.data().description;
li.appendChild(name);
li.appendChild(description);
servicelist.appendChild(li);
}

但是,我一直得到一个未定义的文档错误指向我的

const servicelist = document.querySelector('.service-list');

我尝试做("#service 列表"(没有帮助。这是因为querySelector不适用于JSX,而只能使用HTML?任何建议将不胜感激!

我相信问题是您的const servicelist = document.querySelector...行在文件范围内,这意味着它在加载文件时立即运行,这还为时过早,因为 DOM 尚未加载。 尝试像这样更改代码的第一部分。

import Storefront from './../components/Storefront';
let servicelist;
function init() {
console.log("Initializing");
servicelist = document.querySelector('.service-list');
// anything else you want to do on initialize
}
window.onload = init;
// The rest as you have it already.

这里有一个很好的介绍:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

最新更新