是否有一种方法可以过滤产品列表而不使页面变白?



我使用state创建了一个react产品列表,还创建了一个过滤器来过滤产品。我的问题是当我第二次点击分类按钮时,我的页面消失了。

我尝试不使用状态在内存中存储数据,但没有工作。我的沙盒代码链接在这里。

https://codesandbox.io/s/l1b3od?file=/src/styles.css& resolutionWidth = 612, resolutionHeight = 675

你必须这样修改你的过滤函数:

const Filtfunc = (prod)=>{
const result = Products.filter((x)=>{ // Here's the change
return x.category === prod
})
setData(result)
console.log(result)
}

您过滤的是数据而不是产品,所以一旦第一次过滤,您就没有所有的产品要过滤,只有过滤后的数据。

在您的filter函数中,您尝试通过使用data来过滤Products,但是当您单击任何类别时,您将data设置为结果也可以为空的数组。您必须使用Products来过滤数组,而不是稍后设置的data。因此,它应该是:

const Filtfunc = (prod) => {
const result = Products.filter((x) => {
return x.category === prod;
});
setData(result);
};

你也可以设置if语句来检查你的数组是否返回任何东西:

<div className="create">
{data.length > 0 ? (
data.map((product) => 
// things here
)) : (
<h2>No result has been found</h2>
)}
</div>

最新更新