useEffect 在页面刷新时失败

useEffect fails on page refresh

我是一名初级程序员,我正在尝试获取 api 并使用 React 设置结果样式。我的页面在初始加载和随后在 VScode 上保存时运行良好,但是当我实际从浏览器刷新页面时,我收到了图像 enter image description here:

上发布的错误

这是我的代码: App.js

```import React, { useEffect, useState } from 'react';
import './App.css';

import Students from './components/Students';
import styled from 'styled-components';

function App() {
  const [studentInfo, setStudentInfo] = useState({});
  const [searchResult, setSearchResult] = useState({});
  const [searchTerm, setSearchTerm] = useState('');
  useEffect(() => {
    getStudents();
  }, []);
  useEffect(() => {
    getStudents();
    console.log('useEffect');
  }, [searchTerm]);
  const getStudents = async () => {
    const url = 'https://api.hatchways.io/assessment/students';
    console.log(url);
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        searchTerm != ''
          ? setStudentInfo(filterStudents(data.students))
          : setStudentInfo(data.students);
      });
  };

    const filterStudents = (studentsArray) => {
    return studentsArray.filter((info) => {
      return (
        info.firstName.toLowerCase().includes(searchTerm) ||
        info.lastName.toLowerCase().includes(searchTerm)
      );
    });
  };
  console.log(searchTerm);

  return (
    <div className="App">
      <Students
        studentInfo={studentInfo}
        setSearchTerm={setSearchTerm}
        searchTerm={searchTerm}
      />
    </div>
  );
}

export default App;```

这是我的组件Students.js:

```import React, { useState } from 'react';
import styled from 'styled-components';
import GradeDetails from './GradeDetails';

const Students = ({ studentInfo, searchTerm, setSearchTerm }) => {
  console.log(typeof studentInfo);
  console.log(studentInfo[0]);
  const [isCollapsed, setIsCollapsed] = useState(false);

  const handleDetails = () => {
    setIsCollapsed(!isCollapsed);
  };
  const average = (arr) => {
    let sum = 0;
    arr.map((num) => {
      sum = sum + parseInt(num);
    });
    return sum / arr.length.toFixed(3);
  };
  console.log(isCollapsed);
  return (
    <Container>
      <Input
        type="text"
        value={searchTerm}
        placeholder="Search by name"
        onChange={(e) => setSearchTerm(e.target.value.toLowerCase())}
      />
      {studentInfo?.map((student) => (
        <Wrapper key={student.id}>
          <ImageContainer>
            <Image src={student.pic}></Image>
          </ImageContainer>
          <ContentContainer>
            <Name>
              {student.firstName} {student.lastName}{' '}
            </Name>
            <Email>Email: {student.email}</Email>
            <Company>Company: {student.company}</Company>
            <Skills>Skill: {student.skill}</Skills>

            <Average>Average:{average(student.grades)}%</Average>
          </ContentContainer>
          <ButtonContainer>
            <Button onClick={handleDetails}>+</Button>
          </ButtonContainer>
          {isCollapsed && <GradeDetails studentInfo={studentInfo} />}
        </Wrapper>
      ))}
    </Container>
  );
};```

每次出现错误时,我都会注释掉 Students.js 中从 studentInfo.map 开始的代码,然后保存,然后取消注释并保存,然后一切正常。

我希望每次都能有人帮助我完成这项工作,这样我就不必一直坐在座位的边缘了。谢谢你,对于这么长的问题我深表歉意。

您正在使用空 对象 作为 studentInfo 的初始状态(传递给 useState 挂钩的值将用作默认值 - docs):

const [studentInfo, setStudentInfo] = useState({});

.map 仅在 数组 上受支持。因此,当组件在 useEffect 完成并将 studentInfo 的值从对象更新为数组之前呈现时,这是失败的。尝试将初始状态交换为数组:

const [studentInfo, setStudentInfo] = useState([]);