列出对象列表中的项目一次 ReactJS
List items in object list once ReactJS
我有这个文件:
ProductList.js
import React from "react";
export default function ProductList() {
document.addEventListener("DOMContentLoaded", () => {
var listeditems = {};
const list = document.getElementById("list");
if (items !== null) {
for (let f = 0; f < Object.keys(items).length; f++) {
const item = items[f];
if (!Object.keys(items).includes(item.name)) {
listeditems[item.name] = null;
list.innerHTML +=
"<p>" + item.name + ", sells for €" + item.price + "</p>";
}
}
} else {
list.innerText = "None yet!";
}
});
return (
<span id="list"></span>
);
}
在 App.js 中呈现如下:
import ProductList from './ProductList';
return(
// Something
<ProductList/>
// And more...
);
其中 items
是 {"0":{"name":"Banana","price":"0.22"}}
。这输出这个:
<span id="list"><p>Banana, sells for €0.22</p><p>Banana, sells for €0.22</p></span>
如您所见,<p>Banana, sells for €0.22</p>
在其中出现两次,而在对象(列表)中只出现一次。
我如何防止这种情况发生?,我如何只为列表中的每个项目获取一个 <p>...</p>
。
var out;
if (items !== null) {
for (let f = 0; f < Object.keys(items).length; f++) {
const item = items[f];
if(item.name !== undefined){
out += "<li>" + item.name + ", sells for €" + item.price + "</li>";
}
}
window.addEventListener('DOMContentLoaded', () => {
document.getElementById("list").innerHTML= out.replace("undefined", "");
});
} else {
window.addEventListener('DOMContentLoaded', () => {
document.getElementById("list").innerHTML="<li>None yet</li>";
});
}
return (
<div>
<h3>A list of your products</h3>
<ul id="list"></ul>
</div>
);
我有这个文件:
ProductList.js
import React from "react";
export default function ProductList() {
document.addEventListener("DOMContentLoaded", () => {
var listeditems = {};
const list = document.getElementById("list");
if (items !== null) {
for (let f = 0; f < Object.keys(items).length; f++) {
const item = items[f];
if (!Object.keys(items).includes(item.name)) {
listeditems[item.name] = null;
list.innerHTML +=
"<p>" + item.name + ", sells for €" + item.price + "</p>";
}
}
} else {
list.innerText = "None yet!";
}
});
return (
<span id="list"></span>
);
}
在 App.js 中呈现如下:
import ProductList from './ProductList';
return(
// Something
<ProductList/>
// And more...
);
其中 items
是 {"0":{"name":"Banana","price":"0.22"}}
。这输出这个:
<span id="list"><p>Banana, sells for €0.22</p><p>Banana, sells for €0.22</p></span>
如您所见,<p>Banana, sells for €0.22</p>
在其中出现两次,而在对象(列表)中只出现一次。
<p>...</p>
。
var out;
if (items !== null) {
for (let f = 0; f < Object.keys(items).length; f++) {
const item = items[f];
if(item.name !== undefined){
out += "<li>" + item.name + ", sells for €" + item.price + "</li>";
}
}
window.addEventListener('DOMContentLoaded', () => {
document.getElementById("list").innerHTML= out.replace("undefined", "");
});
} else {
window.addEventListener('DOMContentLoaded', () => {
document.getElementById("list").innerHTML="<li>None yet</li>";
});
}
return (
<div>
<h3>A list of your products</h3>
<ul id="list"></ul>
</div>
);