3 回答

TA貢獻1785條經驗 獲得超8個贊
useEffect(() => {
const fetchData = () => {
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => setData(result))
.catch((err) => console.log("error"));
};
fetchData();
}, []);
function handleChange(e) {
setSearch(e.target.value)
}
return (
<div>
<input
className="input"
type="text"
placeholder="search country ..."
value={search}
onChange={handleChange}
/>
{data &&
data.filter(item=> item.name.includes(search)).map((country) => (
<div className="CountryList" key={country.name}>
<div className="CountryListImg">
<img src={country.flag} alt="" width="80px" />
</div>
<div className="countryName">{country.name}</div>
<div className="population">{country.population}</div>
<div className="region">{country.region}</div>
<div>
{country.languages.map((language, languageIndex) => (
<div key={languageIndex}>{language.name}</div>
))}
</div>
</div>
))}
</div>
);

TA貢獻1824條經驗 獲得超5個贊
您可以在呈現數據時在線過濾。記得做不區分大小寫的字符串比較
data
.filter(
(country) =>
!search || country.name.toLowerCase().includes(search.toLowerCase())
)
.map(country => ...)
如果搜索為假,即""過濾器返回真并返回國家,否則檢查國家名稱是否包含搜索值。
保存輸入值
function handleChange(e) {
const { value } = e.target;
setSearch(value);
}

TA貢獻1850條經驗 獲得超11個贊
首先,如果你沒有安裝 lodash
npm install lodash
并使用去抖動
// Lodash here <<<<<<<<<<<<<<<<
import { debounce } from 'lodash';
export default function CountryList() {
const [data, setData] = useState([]);
const [search, setSearch] = useState("");
const fetchData = (text) => {
// Fix your API with text search here <<<<<<<<<<<<<<,
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => setData(result))
.catch((err) => console.log("error"));
};
useEffect(() => {
fetchData();
}, []);
function handleChange(e) {
setSearch(e)
onSearch(e)
console.log(e.target.value);
}
const onSearch = debounce((text) => {
fetchData(text);
}, 500)
return (
<div>
<input
className="input"
type="text"
placeholder="search country ..."
value={search}
onChange={handleChange}
/>
{data &&
data.map((country) => (
<div className="CountryList" key={country.name}>
<div className="CountryListImg">
<img src={country.flag} alt="" width="80px" />
</div>
<div className="countryName">{country.name}</div>
<div className="population">{country.population}</div>
<div className="region">{country.region}</div>
<div>
{country.languages.map((language, languageIndex) => (
<div key={languageIndex}>{language.name}</div>
))}
</div>
</div>
))}
</div>
);
}
添加回答
舉報