响应异步API调用



我正在尝试理解其他人的代码,我有这个组件:

import React from 'react';
import { useEffect, useState } from 'react';
export default function CountriesList({ searchValue }) {
const [data, setData] = useState([])
//Onmount
useEffect(() => {
async function init() {
//API Calls- request data from the server
const response = await fetch('https://restcountries.com/v2/all');
const body = await response.json();
setData(body);
}
init()
}, [])//dependencies array
return (
<div className="countries-container">
{data
.filter(country => country.name.toLowerCase().includes(searchValue.toLowerCase()))
.map((country) => {
const { name, flag } = country;
return (
<div key={name} className="country-container">
<h3 className="title">{name}</h3>
<img src={flag} height="100px" width="100px" alt="flag" />
</div>
)
})}
</div>
)
}

在init((中,程序员再次调用init((,你能解释一下为什么吗?我试着寻找这种风格的编程,但一无所获。清空这行API调用不起作用。

谢谢!

我可能错了,但据我所见,init函数是在声明后立即声明和调用的。

看看这个:https://github.com/facebook/react/issues/14326

最新更新