我试图将提取请求中的数据存储到状态中,但是即使在没有依赖项的情况下,它也会以无限循环结束。当我移除div中的代码,将其过滤并映射出数组时,它似乎不是无限循环,但我不知道为什么过滤/映射会导致它这样循环。
function App() {
const [searchTerm, setSearchTerm] = useState("");
const [students, setStudents] = useState([]);
const [isActive, setIsActive] = useState(false);
const average = (array) => {
return array.reduce((a, b) => a + parseFloat(b), 0) / array.length;
};
useEffect(() => {
const api = async () => {
await fetch("https://api.hatchways.io/assessment/students")
.then((res) => res.json())
.then((data) => setStudents(data.students));
};
api();
}, []);
return (
<div className='bg-gray-300 h-screen flex items-center justify-center'>
{students
.filter((student) => {
if (searchTerm === "") {
return student;
} else if (
student.firstName
.toLowerCase()
.includes(searchTerm.toLowerCase()) ||
student.lastName.toLowerCase().includes(searchTerm.toLowerCase())
) {
return student;
}
})
.map((student, i) => (
<div
key={i}
className='flex items-center space-x-8 px-8 py-3 border-b'>
<div className='flex items-start w-full space-x-7'>
<div className='border overflow-hidden rounded-full'>
<img
className='w-24 h-24 bg-contain'
src={student?.pic}
alt='student school portrait'
/>
</div>
<div className='flex flex-col justify-between space-y-4 w-full'>
<div className='flex items-center justify-between'>
<h1 className='font-bold text-5xl'>
{student?.firstName} {student?.lastName}
</h1>
<button onClick={setIsActive(!isActive)}>
{isActive ? (
<AiOutlinePlus className='h-7 w-7' />
) : (
<AiOutlineMinus className='h-7 w-7' />
)}
</button>
</div>
<div className='pl-3'>
<p>Email: {student?.email}</p>
<p>Company: {student?.company}</p>
<p>Skill: {student?.skill}</p>
<p>Average: {average(student?.grades).toFixed(2)}%</p>
</div>
</div>
</div>
</div>
))}
</div>
);
}发布于 2021-12-07 09:39:18
如果使用async/await,则不需要链接.then()。尝试将您的useEffect更新为:
useEffect(() => {
api();
}, []);
const api = async () => {
let res = await fetch("https://api.hatchways.io/assessment/students");
let data = await res.json();
setStudents(data.students)
}; 此外,在按钮单击处理程序中使用箭头函数,如:
<button onClick={()=>setIsActive(!isActive)}>发布于 2021-12-07 09:53:02
大多数情况下,我尝试在useEffect中调用函数,而在useEffect之外对函数进行编码。这对我有用,试试吧。
useEffect(() => {
api();
}, []);
const api = async () => {
await fetch("https://api.hatchways.io/assessment/students")
.then((res) => res.json())
.then((data) => setStudents(data.students));
};发布于 2021-12-07 09:47:52
尝试使用async-await语法
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
"https://api.hatchways.io/assessment/students"
);
const result = await response.json();
console.log("res", result);
};
fetchData();
}, []);如果您想要处理错误,您需要添加try catch块。
https://stackoverflow.com/questions/70257707
复制相似问题