[英]array wont render on React state change
I have this useState hook:我有这个 useState 钩子:
const [products, setProducts] = useState([])
and I have these functions:我有这些功能:
const sortByLow =()=>{
const newArray = products.sort((a,b)=>b.price-a.price)
setProducts(newArray)
console.log(newArray);
}
const sortByHigh =()=>{
const newArray = products.sort((a,b)=>a.price-b.price)
setProducts(newArray)
console.log(newArray);
}
a useEffect hook:一个 useEffect 钩子:
useEffect(()=>{
const displayProducts = async()=>{
try {
//fetch from server at port 3000
const response = await fetch('http://localhost:3000/')
if(!response.ok){
throw new Error("displayProducts response is not ok")
}
const responseDataObject = await response.json()
const allProducts = responseDataObject.data.allProducts
setProducts(allProducts);
} catch (error) {
console.log("theres an error" + error);
}
}
//call the function, duh
displayProducts();
}, [])
and the return value of the component is this:组件的返回值是这样的:
<div>
{products.filter( product => {return (product.price > lowPrice && product.price < highPrice)} ).map(productObj => <ProductComponent
navigateToProduct = {productObj._id}
navigateToCategory = {productObj.category}
key = {productObj._id}
name = {productObj.name}
category = {productObj.category}
price = {productObj.price}
description = {productObj.description}
image = {productObj.image}
/>)}
</div>
now I expect the product array to change according to the functions above but it wont happen for some reason.现在我希望产品数组会根据上面的功能发生变化,但由于某种原因它不会发生。 what can be the problem?
可能是什么问题? please help me thanks!
请帮帮我谢谢!
ok I figured it out thanks to @KonradLinkowski comment... The sort only references the original array, so in order to create a new array I should have written [...products]
as the source array, as follows:好的,感谢@KonradLinkowski 的评论,我明白了...排序仅引用原始数组,因此为了创建一个新数组,我应该将
[...products]
编写为源数组,如下所示:
const sortByLow =()=>{
const newArray = [...products].sort((a,b)=>b.price-a.price)
setProducts(newArray)
console.log(newArray);
}
const sortByHigh =()=>{
const newArray = [...products].sort((a,b)=>a.price-b.price)
setProducts(newArray)
console.log(newArray);
}
Thanks to all who read and helped!感谢所有阅读和帮助的人!
When you sort through an array it does not make a new reference ID so it does not know to update the state.当您对数组进行排序时,它不会生成新的参考 ID,因此它不知道更新 state。 This is how you can force it to make a new reference
这就是您可以强制它做出新参考的方式
const sortByLow = () => {
const newArray = [...products];
newArray.sort((a, b) => b.price - a.price);
setProducts(newArray);
console.log(newArray);
};
const sortByHigh = () => {
const newArray = [...products];
newArray.sort((a, b) => a.price - b.price);
setProducts(newArray);
console.log(newArray);
};
This should update the react state这应该更新反应 state
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.