我有处理搜索功能的类组件函数。
filterData(offers,searchKey){
const result = offers.filter((offer) =>
offer.value.toLowerCase().includes(searchKey)||
offer.expiryDate.toLowerCase().includes(searchKey)||
offer.quantity.toLowerCase().includes(searchKey)
)
this.setState({offers:result})
}
const handleSearchArea = (e) =>{
const searchKey=e.currentTarget.value;
axios.get(`/viewPendingSellerOffers`).then(res=>{
if(res.data.success){
this.filterData(res.data.existingOffers,searchKey)
}
});
}
现在我尝试将这些类组件函数转换为功能组件函数。为此,我尝试了这种方式。
const filterData = (offers,searchKey) => {
const result = offers.filter((offer) =>
offer.value.toLowerCase().includes(searchKey)||
offer.expiryDate.toLowerCase().includes(searchKey)||
offer.quantity.toLowerCase().includes(searchKey)
)
setState({offers:result})
}
const handleSearchArea = (e) =>{
const searchKey=e.currentTarget.value;
axios.get(`/viewPendingSellerOffers`).then(res=>{
if(res.data.success){
filterData(res.data.existingOffers,searchKey)
}
});
}
但是我收到一条错误消息,指出“'setState' 未定义”。我该如何解决这个问题?
解决方案:
import React, {useState} from "react";
import axios from "axios";
const YourFunctionalComponent = (props) => {
const [offers, setOffers] = useState()
const filterData = (offersPara, searchKey) => {// I changed the params from offers to offersPara because our state called offers
const result = offersPara.filter(
(offer) =>
offer?.value.toLowerCase().includes(searchKey) ||
offer?.expiryDate.toLowerCase().includes(searchKey) ||
offer?.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 (
//To use your *offers* state object just call it like this {offers?.El1?.El2}
);
};
export default YourFunctionalComponent;
注意:建议在访问这样的嵌套对象之前进行空检查res?.data?.existingOffers
,Optional chaining将在这方面帮助我们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句