【发布时间】:2020-10-30 08:57:22
【问题描述】:
我对 JavaScript 和 React 很陌生,我有一个初学者级别的问题。在这里,我尝试从 API 中获取一些数据并将其消除为我所需要的(国家的全名及其简短版本)。 我想在材质 UI 组合框中列出国家/地区列表,并以两种方式显示它们: 在打开国家列表的情况下,首先要完整显示名称。 其次,在从列表中选择国家的情况下,显示他们的简短形式,如(美国)。 我怎样才能使第二个目标成为可能?为什么在第 47 行,我无法解析 country.value ? 提前感谢您的宝贵时间。
import './App.css';
import {FormControl, TextField} from '@material-ui/core';
import React, { useState, useEffect} from "react";
import { Autocomplete } from '@material-ui/lab';
function App() {
const [countries, setCountries] = useState([]);
const [country, setCountry] = useState(['worldwide']);
useEffect(() => {
const getCountriesData = async() => {
await fetch("https://disease.sh/v3/covid-19/countries")
.then((response) => response.json())
.then((data) => {
const countries =data.map((country) => (
{
name: country.country,
value: country.countryInfo.iso2
}
))
setCountries(countries)
})
}
getCountriesData()
}, [])
const onCountryChange = async (event) => {
const countryCode = event.target.value
setCountry(countryCode)
}
return (
<div className="App">
<div className="app__header">
<h1>
Country names!
</h1>
<FormControl className="app__dropDown">
<Autocomplete
options={countries}
getOptionLabel={(country) => country.name}
style={{ width: 200 }}
onChange={onCountryChange}
renderInput={country => (
<TextField
{...country}
label="Choose a Country"
variant="outlined"
placeholder="Choose a Country"
/>
)}
/>
</FormControl>
</div>
</div>
);
}
export default App;
【问题讨论】:
-
我建议你更新问题标题
-
您好,欢迎来到 SO。请在编写问题时查看操作指南。你的标题不是很好,因为它没有描述你的问题。
标签: reactjs material-ui