我正在尝试对我的对象数组进行排序,但它不起作用。有人能明白为什么它不起作用吗?
function App(){
let products = [
{
name: "LED",
price: 50000,
status: true,
image: "images/products/Krunch-Combo-kfc.png"
},
{
name: "Bike",
price: 40000,
status: false,
image: "images/products/Krunch-Combo-kfc.png"
},
{
name: "Mobile",
price: 60000,
status: true,
image: "images/products/Krunch-Combo-kfc.png"
},
{
name: "Apple Watch",
price: 6000,
status: true,
image: "images/products/Krunch-Combo-kfc.png"
}
];
return (
<div>
<ul>
{
products.sort((a, b) => parseFloat(a.price) - parseFloat(b.price))
}
</ul>
</div>
)
}
export default App;
这是我得到的错误。 错误:对象作为 React 子对象无效(找到:带有键 {name, price, status, image} 的对象)。如果您打算渲染一组子项,请改用数组。
答案 0 :(得分:0)
import { useMemo } from "react";
let products = [
{
name: "LED",
price: 50000,
status: true,
image: "images/products/Krunch-Combo-kfc.png"
},
{
name: "Bike",
price: 40000,
status: false,
image: "images/products/Krunch-Combo-kfc.png"
},
{
name: "Mobile",
price: 60000,
status: true,
image: "images/products/Krunch-Combo-kfc.png"
},
{
name: "Apple Watch",
price: 6000,
status: true,
image: "images/products/Krunch-Combo-kfc.png"
}
];
function App() {
const memoizedProducts = useMemo(
() =>
products.sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
if (priceA < priceB) return -1;
if (priceA > priceB) return 1;
return a.name.localeCompare(b.name);
}),
[]
);
return (
<div>
<ul>
{memoizedProducts.map(({ name, price }, index) => (
<li key={index}>
{name} - {price}
</li>
))}
</ul>
</div>
);
}
export default App;
答案 1 :(得分:0)
缩短数组后,你想用它们做什么?
答案 2 :(得分:0)
function App() {
let products = [
{
name: "LED",
price: 50000,
status: true,
image: "images/products/Krunch-Combo-kfc.png",
},
{
name: "Bike",
price: 40000,
status: false,
image: "images/products/Krunch-Combo-kfc.png",
},
{
name: "Mobile",
price: 60000,
status: true,
image: "images/products/Krunch-Combo-kfc.png",
},
{
name: "Apple Watch",
price: 6000,
status: true,
image: "images/products/Krunch-Combo-kfc.png",
},
];
const sortedProducts = products.sort(
(productA, productB) =>
parseFloat(productA.price) - parseFloat(productB.price)
);
return (
<div className="app">
<ul>{JSON.stringify(sortedProducts)}</ul>
</div>
);
}
export default App;
为了呈现 jsx
中 DOM
中的产品,请使用高阶数组函数 map
。
祝你好运,如果这就是你要找的,请告诉我