我目前正在使用获取一些数据,并试图对该数据的一些道具执行操作。
我正试着这样获取我的学生名单:
const [studentDetails, setStudentDetails] = useState([]);
const [collegeOpportunities, setCollegeOpportunities] = useState([]);
useEffect(() => {
fetch("/api/v1/students/1022")
.then(response => response.json())
.then(response => {
setStudentDetails(response);
setCollegeOpportunities(studentDetails.Opportunities)
setIsLoading(false);
})
.catch(error => console.log(error));
}, []);
然后,当我尝试对collegeOpportunities
执行一些操作时,我收到了错误。我尝试运行的功能是:
const dropdownFilter = collegeOpportunities.filter(opportunity =>{
return(
opportunity.type.indexOf(dropdownValue) >= 0
)
})
const filteredOpportunities = dropdownFilter.filter(opportunity => {
return (
opportunity.description.toLowerCase().indexOf(filterValue.toLowerCase()) >= 0 ||
opportunity.id.toLowerCase().indexOf(filterValue.toLowerCase()) >= 0
);
});
在collegeOpportunities.filter
上,我接收Cannot read property 'filter' of undefined
对我来说,这似乎是一个异步问题,就像我试图在设置collegeOpportunities
之前访问它们一样。有什么建议吗?我该怎么解决?
setCollegeOpportunities(studentDetails.Opportunities)
setStudentDetails
异步更新状态。所以,上面一行中的studentDetails
并不是你所期望的。它实际上是在做[].Opportunities
,也就是undefined
。
请尝试以下操作。
setCollegeOpportunities(response.Opportunities)
确保密钥Opportunities
存在于服务器响应中并且是一个数组。否则,当filter
正在进行时,您将遇到TypeError
尝试:
(collegeOpportunities || []).filter(...