Javascript 未捕获类型错误:无法读取属性';过滤器';通过道具后未定义的。反应
我目前正在使用获取一些数据,并尝试对这些数据的一些道具执行操作 我试着像这样获取我的学生名单:Javascript 未捕获类型错误:无法读取属性';过滤器';通过道具后未定义的。反应,javascript,reactjs,Javascript,Reactjs,我目前正在使用获取一些数据,并尝试对这些数据的一些道具执行操作 我试着像这样获取我的学生名单: const [studentDetails, setStudentDetails] = useState([]); const [collegeOpportunities, setCollegeOpportunities] = useState([]); useEffect(() => { fetch("/api/v1/students/1022") .th
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上,我收到无法读取未定义的属性“filter”
这对我来说似乎是一个异步问题,就像我在设置collegeOpportunities
之前试图访问它们一样。您有什么建议吗?我该如何解决它?试试:
(collegeOpportunities || []).filter(...
setCollegeOpportunities(studentDetails.Opportunities)
setStudentDetails
异步更新状态。因此,上面一行中的studentDetails
不是您所期望的。它实际上是在做[].Opportunities
,它是未定义的
尝试以下方法
setCollegeOpportunities(response.Opportunities)
确保密钥Opportunities
存在于服务器响应中,并且是一个数组。否则,当filter
ing不起作用时,您将遇到TypeError
s。从am空数组加载,然后呢?当道具加载时,它会一直空着,应该再试一次…谢谢你。这解释了很多。我真是太傻了,竟然这样装。