我是新手,刚开始学习。我正在尝试根据产品的价格对对象进行排序。但是当我尝试更新状态时它不会改变虽然当我执行 console.log() 我可以看到排序的产品但它根本不会在屏幕上更新。我附上下面的代码。任何帮助将不胜感激。
当我打开应用程序时。我看到我所有的产品。但是当我使用选择框对产品进行排序时,它只会向我显示相同的产品而没有排序。事件被触发。但我怀疑我更新状态的方式是错误的。
import './main.css'
import Filters from './components/Filters'
import Products from './components/Products'
import { useState } from 'react';
function App() {
const [products,setProducts]=useState([
{product_id:'1',product_name:"Razer Deathadder expert ergonomic mousepad",product_price:"20",product_path:"img/razer-deathadder-expert-ergonomic-original-imaf2z3xngbchfaz.jpeg"},
{product_id:'2',product_name:"Zotac gtx 1080 graphics card",product_price:"320",product_path:"img/grap.jpg"},
{product_id:'3',product_name:"Kingston 250 gb SSD ",product_price:"90",product_path:"img/ssd.jpg"},
{product_id:'4',product_name:"Ryzen Processor",product_price:"250",product_path:"img/ry.jpg"}
]);
let sortedProducts=[]
const sortProducts=(e)=>{
const sortBy=String(e.target.value);
switch(sortBy){
case 'plh': // sorting based on price low to high
sortedProducts=products.sort((x,y)=>{
return Number(x.product_price)-Number(y.product_price);
});
setProducts(sortedProducts); // I'm chaning the state here with my newly sorted array but its not rendering on screen
break;
case 'phl':
sortedProducts=products.sort((x,y)=>{
return Number(y.product_price)-Number(x.product_price);
});
setProducts(sortedProducts); // I'm chaning the state here with my newly sorted array but its not rendering on screen
break;
}
}
return (
<div className="App">
<div className="container">
<Filters sortProducts={sortProducts}/>
<Products products={products} />
</div>
</div>
);
}
export default App;
这是产品组件
import Product from './Product'
function Products({products}) {
return (
<div className="product-container">
{products.map(element => (
<Product product={element}/>
))}
</div>
);
}
export default Products;