gpt4 book ai didi

javascript - 如何按值(value)对产品进行排序?

转载 作者:行者123 更新时间:2023-12-04 14:04:09 25 4
gpt4 key购买 nike

我有对象数组 products 就像

[{name: 'apple', value: 100}, {name: 'watermelon', value: 200}, {name: 'orange', value: 50}], 和一个选择带有“高价”和“低价”选项的输入,但它不起作用:

function ProductsPage() {
const [products, setProducts] = useState([])

useEffect(() => {/*here i setProducts([...]) array of objects which i get of backend*/})

const orderShowing = (e) => {
let actual_show = products
let newOrder = e.target.value;
if (newOrder === "High price") {
actual_show.sort((a, b) => (b.value > a.value) ? 1 : (a.value > b.value) ? -1 : 0)
} else if (newOrder === "Low price") {
actual_show.sort((a, b) => (a.value > b.value) ? 1 : (b.value > a.value) ? -1 : 0)
console.log(actual_show)
setProducts(actual_show)
}

return (
<div>
<select id="productsOrder" onChange={orderShowing}>
<option>High price</option>
<option>Low price</option>
</select>
<h2>Products</h2>
{products.map((p) => {
return <p>{p.name}</p>})}
</div>
)
}

console.log 实际上是我想要的(排序有效),但页面不会用"new"products 数组刷新

最佳答案

首先,您需要复制您的状态:

  let actual_show = [...products];

然后尝试像我正在使用的那样对其进行排序:

import { useEffect, useState } from "react";

export default function App() {
const [products, setProducts] = useState([
{ name: "apple", value: 100 },
{ name: "watermelon", value: 200 },
{ name: "orange", value: 50 }
]);

const orderShowing = (e) => {
let actual_show = [...products];
let newOrder = e.target.value;
if (newOrder === "High price") {
actual_show.sort((a, b) => a.value - b.value);
} else if (newOrder === "Low price") {
actual_show.sort((a, b) => b.value - a.value);
}
setProducts(actual_show);
};

return (
<div>
<select id="productsOrder" onChange={orderShowing}>
<option>High price</option>
<option>Low price</option>
</select>
<h2>Products</h2>
{products.map((p) => {
return <p>{p.name}</p>;
})}
</div>
);
}

Edit gracious-darkness-gjk6k

关于javascript - 如何按值(value)对产品进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69082246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com