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

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

   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在服务器响应中存在并且是数组。否则,TypeError会遇到filter s。

关于javascript - Uncaught TypeError:传递 Prop 后无法读取未定义的属性“filter”。 React.js,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60941561/

10-16 23:43