我目前正在使用来获取一些数据,并且正在尝试对该数据的某些道具进行操作。
我正在尝试这样获取我的名单上的学生:
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
之前尝试访问它们。究竟是什么建议还是我该如何解决?
答案 0 :(得分:1)
setCollegeOpportunities(studentDetails.Opportunities)
setStudentDetails
异步更新状态。因此,上一行中的studentDetails
并不是您期望的。它实际上在做[].Opportunities
,即undefined
。
尝试以下操作。
setCollegeOpportunities(response.Opportunities)
确保键Opportunities
存在于服务器响应中并且是数组。否则,TypeError
插入时会遇到filter
s。
答案 1 :(得分:0)
尝试:
(collegeOpportunities || []).filter(...