2 回答
TA贡献1871条经验 获得超8个赞
我不确定这是否是问题所在,但我认为你想要改变
if (!checkedInputs || Object.keys(checkedInputs).every(value => checkedInputs[value] === false)) {
return <ProductCard item={item} key={item.itemID} />
}
到
if (Object.keys(checkedInput).length < 1 || Object.keys(checkedInputs).every(value => checkedInputs[value] === false)) {
return <ProductCard item={item} key={item.itemID} />
}
空对象的计算结果为 true。我认为一个对象总是会评估为 true。(Try Boolean({}) and Boolean({x:5}))。另外,我有点困惑(我可能会遗漏一些东西),为什么你在 Object.entries(checkedInputs) 的每次迭代中调用 Object.keys(checkedInputs).every 。该值不会改变,对吗?那么它不能是你在循环之前设置的静态值吗?
TA贡献1993条经验 获得超5个赞
const Products = (props) => {
const { Item } = props.items
const { Category } = props.categories
const [checkedInputs, setCheckedInputs] = useState({})
const handleInputChange = (event) => {
setCheckedInputs({ ...checkedInputs, [event.target.value]: event.target.checked })
}
useEffect(() => {
console.log('Checked Inputs', checkedInputs)
}, [checkedInputs])
function renderItems(){
let hasNoFilters = Object.keys(checkedInput).length < 1 ||
Object.keys(checkedInputs).every(value =>checkedInputs[value] === false)
if(hasNoFilters){
// return everything if no filter
return Item.map(item=>return <ProductCard item={item} key={item.itemID} />)
}
else{
let filters = Object.keys(checkedInput).filter(itemID=>checkedInput[itemID] === true)
return Item.map(item=>{
//check to make sure itemID is found in filters
let validItem = filters.find(itemID=>itemID === item.itemID)
if(!validItem)
return
return <ProductCard item={item} key={item.itemID} />
})
}
}
return (
<Layout>
<div className="flex mx-96">
<div className="w-1/4">
<ProductFilter category={Category} handleInputChange={handleInputChange} checkedInputs={checkedInputs} />
</div>
<div className="w-3/4">
<div className="lg:grid grid-cols-3 gap-2 lg:my-12 lg:justify-center">
{renderItems()}
</div>
</div>
</div>
</Layout>
)
}
添加回答
举报