Uncaught TypeError:传递道具后无法读取未定义的属性“ filter”。 React.js

时间:2020-03-31 00:21:31

标签: javascript reactjs

我目前正在使用来获取一些数据,并且正在尝试对该数据的某些道具进行操作。

我正在尝试这样获取我的名单上的学生:

   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之前尝试访问它们。究竟是什么建议还是我该如何解决?

2 个答案:

答案 0 :(得分:1)

setCollegeOpportunities(studentDetails.Opportunities)

setStudentDetails异步更新状态。因此,上一行中的studentDetails并不是您期望的。它实际上在做[].Opportunities,即undefined

尝试以下操作。

setCollegeOpportunities(response.Opportunities)

确保键Opportunities存在于服务器响应中并且是数组。否则,TypeError插入时会遇到filter s。

答案 1 :(得分:0)

尝试:

(collegeOpportunities || []).filter(...