gpt4 book ai didi

javascript - React JS 排序问题

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

我正在尝试对我的应用程序中的一些数据进行排序。我想支持以下选项:

  • 价格(从低到高)
  • 价格(从高到低)
  • 里程(从低到高)
  • 里程(从高到低)

看起来价格排序起作用了。然而,当我点击“最低里程”时,它一直显示最高价格结果——sorting 的旧值。我尝试了 useEffect,但我无法让它工作。这是我的代码:

App.js

      
const [carList, setCarList] = useState(cars)
const [sorting, setSorting] = useState("pricelow")

const handleSort = (e) => {
setSorting(e.target.value)
if (sorting === "pricelow"){
const newlist = carList.sort((a,b) => {
return parseInt(b.carPrice) - parseInt(a.carPrice)
})
setCarList(newlist)
}
if (sorting === "pricehigh"){
const newlist = carList.sort((a,b) => {
return parseInt(a.carPrice) - parseInt(b.carPrice)
})
setCarList(newlist)
}
if (sorting === "kmlow"){
const newlist = carList.sort((a,b) => {
return parseInt(a.carMileage) - parseInt(b.carMileage)
})
setCarList(newlist)
}
}

AdsList.js

      <select className="form-select w-25" onChange={handleSort} value={sorting}>
<option value="pricelow">Sort By Lowest Price</option>
<option value="pricehigh">Sort By Highest Price</option>
<option value="kmlow">Sort By Lowest Km</option>
<option value="kmhigh">Sort By Highest Km</option>
</select>

最佳答案

发生这种情况是因为 setSorting 不会立即更改 sorting 值,而是等到组件重新呈现。参见 https://reactjs.org/docs/react-component.html#setstate

改为这样做:

 const [sorting, setSorting] = useState("pricelow")

const handleSort = (e) => {
const sortValue = e.target.value;
setSorting(sortValue)

if (sortValue === "pricelow"){
const newlist = carList.sort((a,b) => {
return parseInt(b.carPrice) - parseInt(a.carPrice)
})
setCarList(newlist)
}
if (sortValue === "pricehigh"){
const newlist = carList.sort((a,b) => {
return parseInt(a.carPrice) - parseInt(b.carPrice)
})
setCarList(newlist)
}
if (sortValue === "kmlow"){
const newlist = carList.sort((a,b) => {
return parseInt(a.carMileage) - parseInt(b.carMileage)
})
setCarList(newlist)
}
}

另一个提示,使用 switch/case 来获得更清晰的代码。

关于javascript - React JS 排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69315921/

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