在 ReactJS 中列出数组中的所有项目
List all items in an array in ReactJS
这是我在 App.js 中渲染的文件:
ProductList.js
import React from 'react'
export default function ProductList() {
var items = JSON.parse(localStorage.getItem("products")); //[foo: "4.43", bar: "3.25"]
const listitems = () => {
for( var p in items) {
<p>{p}, {items[p]}</p>
}
}
return (
<div>
{listitems}
</div>
);
}
这不会输出花。
问题是:如何列出数组中的所有项目,如“foo, 4.43”...?
return (
{items.map((el) => (
<p>{el}</p>
)}
)
我想这段代码有一些问题。
首先,您从 localStorage
获得的 products
是一个数组,因此您将无法获得其中的 key:value
对。
您最好将 products
转换为对象,例如:
{
foo: "4.43",
bar: "3.25"
}
然后,一种替代方法是通过执行 const productKeys = Object.keys(products)
来获得 keys
。然后通过它们映射并显示值:
const listItems = productKeys.map(key => <p>{key}: {products[key]}</p>)
return {
<div>
{listItems}
</div>
}
这是我在 App.js 中渲染的文件:
ProductList.js
import React from 'react'
export default function ProductList() {
var items = JSON.parse(localStorage.getItem("products")); //[foo: "4.43", bar: "3.25"]
const listitems = () => {
for( var p in items) {
<p>{p}, {items[p]}</p>
}
}
return (
<div>
{listitems}
</div>
);
}
这不会输出花。
问题是:如何列出数组中的所有项目,如“foo, 4.43”...?
return (
{items.map((el) => (
<p>{el}</p>
)}
)
我想这段代码有一些问题。
首先,您从 localStorage
获得的 products
是一个数组,因此您将无法获得其中的 key:value
对。
您最好将 products
转换为对象,例如:
{
foo: "4.43",
bar: "3.25"
}
然后,一种替代方法是通过执行 const productKeys = Object.keys(products)
来获得 keys
。然后通过它们映射并显示值:
const listItems = productKeys.map(key => <p>{key}: {products[key]}</p>)
return {
<div>
{listItems}
</div>
}