我正在做一个React代码,它应该从cardInfo中获取每个值并将其放入卡中,并能够搜索和过滤每张卡,这很好地工作,过滤器也是如此。虽然当我用const [searchTerm,setSearchTerm] = useState('');最后我得到了一个白色的屏幕。
import React from "react";
import { useState } from "react/cjs/react.production.min";
import '../css/productFilters.css';
function ProductsFilter(){
const cardInfo=[
{image:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQz3fIWD8EQsvcN8vjqj3RBFXOt0Ybr1C5v5g&usqp=CAU",title:"Lebron James",text:"The worst"},
{image:"https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iRvzLV4Dj3Y4/v0/1200x-1.jpg",title:"James Harden",text:"Meh"},
{image:"https://i.insider.com/5a0dc09a3dbef484008b67e7?width=1000&format=jpeg",title:"Speph Curry",text:"Good"},
{image:"https://depor.com/resizer/Wtf5Y1e8fWd5zRd3Do6yRgV58Fg=/580x330/smart/filters:format(jpeg):quality(75)/cloudfront-us-east-1.images.arcpublishing.com/elcomercio/IKJYQ4ZQ7RFWZFE57TNEBKD5SQ.jpg",title:"Michael Jordan",text:"GOAT"},
]
const renderCard=(card,index)=>{
return(
<ul className="card">
<li><img src={card.image}></img></li>
<li><p className="tittle-card">{card.title}</p></li>
<li><p className="text-card">{card.text}</p></li>
</ul>
)
}
const [searchTerm, setSearchTerm] = useState('');
return (
<div>
<input
type="text"
placeholder="Search..."
onChange={ (event) => setSearchTerm(event.target.value)}
/>
<div className="container">
{cardInfo.filter((val)=>{
if (searchTerm==""){
return val
}
else if (val.title.toLocaleLowerCase().includes(searchTerm.toLocaleLowerCase())){
return val
}
}).map(renderCard)}
</div>
</div>
)
}
export default ProductsFilter
2条答案
按热度按时间avwztpqn1#
感谢Prograk:
导入useState错误。尝试从react ie导入useState。import React,{useState } from“react”- prograk
代码现在正在工作!我留下答案
xfb7svmp2#
对我来说,问题不在于我错误地导入了
useState
,而是我在App
函数之外声明了它。像这样在我的函数中使用
useState
,为我修复了它: