我刚开始使用react,我正在做一个小项目,它使用搜索栏来查找我从数据库中获得的数据。
我尝试的代码如下:
function AcceptedOffers() {
const buyerId=(localStorage.getItem("userId"));
console.log(buyerId);
const [offers, setOffers] = useState([]);
useEffect(()=>{
getAllOffers();
}, []);
const getAllOffers = async () => {
await axios.get(`/viewPendingSellerOffers`)
.then ((response)=>{
const allNotes=response.data.existingOffers;
setOffers(allNotes);
})
.catch(error=>console.error(`Error: ${error}`));
}
console.log(offers);
const filterData = (offersPara, searchKey) => {
const result = offersPara.filter(
(offers) =>
offers?.value.toLowerCase().includes(searchKey) ||
offers?.quantity.toLowerCase().includes(searchKey)
);
setOffers(result);
};
const handleSearchArea = (e) => {
const searchKey = e.currentTarget.value;
axios.get(`/viewPendingSellerOffers`).then((res) => {
if (res?.data?.success) {
filterData(res?.data?.existingOffers, searchKey);
}
});
};
return(
<div className="posts-b">
<div className="posts__container-b">
<h1>Accepted Offers</h1>
<div className="search_box-b">
<input type="text" placeholder="What are you looking for?" onChange={handleSearchArea}></input>
<i className="fas fa-search"></i>
</div>
<main className="grid-b">
{offers.map((offer,index)=> {
if(offer.status==='accepted' && offer.buyerId===buyerId)
return (
<article>
<div className="text-b">
<h3>Post ID: {index + 1}</h3>
<p>Quantity (Kg): {offer.quantity}</p>
<p>Unit Price (Rs): {offer.value}</p>
<p>Expiry Date: {moment(offer.expiryDate).fromNow()}</p>
<p>Collecting Date: {moment(offer.collectingDate).fromNow()}</p>
<p>Offer Gives: {moment(offer.offerCreatedAt).fromNow()}</p>
</div>
</article>
);
})}
</main>
</div>
</div>
);
}
export default AcceptedOffers;从第一个API调用中,我得到了一个长度为9的对象数组。此图显示了我从第一次API调用中获得的数据。

然后我使用map函数映射这些数据。然后,我创建了一个类似上述代码的搜索函数,并尝试将搜索结果映射到相同的组件中。但是当我输入一个搜索字段作为输入时,我得到了一个错误,显示'Unhandled Rejection (TypeError):offers.value.toLowerCase不是一个函数‘。我已经看了一堆教程,我不太确定如何解决这个问题。
有人能帮我解决这个问题吗?也欢迎对代码的任何其他评论。我是来学习的。
谢谢!
发布于 2021-08-11 10:35:45
代码的问题在于,包含是一个整数,而您试图将其用作字符串(toLowerCase和offers.value是适用于字符串的函数)。因此,要使用它们,只需将offers.value更改为字符串并照常操作即可。因此您的filterData函数将如下所示-
const filterData = (offersPara, searchKey) => {
const result = offersPara.filter(
(offers) =>
offers?.value.toString().toLowerCase().includes(searchKey) ||
offers?.quantity.toString().toLowerCase().includes(searchKey)
);
setOffers(result);
};https://stackoverflow.com/questions/68740211
复制相似问题