React Hooks 很奇怪

React Hooks are wierd

import './App.css';
import { MenuItem, FormControl, Select, Card, CardContent } from "@material-ui/core";

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 = (event) => {
    const countryCode = event.target.value;
    setCountry(countryCode);
  }

  return (
    <div className="app">
      <div className="app__header">
        <h1>Covid-19 Tracker</h1>
        <FormControl className="app__dropdown">
          <Select
            variant="outlined"
            onChange={onCountryChange}
            value={country}
          >
            <MenuItem value="WorldWide">WorldWide</MenuItem>
            {countries.map(country => (<MenuItem value={country.value}>{country.name}</MenuItem>))}

          </Select>

        </FormControl>
      </div>
      {/* Title + Select input dropdown */}

      {/* InfoBoxes */}
      {/* InfoBoxes */}
      {/* InfoBoxes */}

      {/* Table */}
      {/* Graph */}
      {/* Map */}
    </div>
  );
}

export default App;

在上面的代码中,我使用了一个状态 country,我通过 setCountry 更新它,具体取决于用户从 select 下拉选项中选择的内容。我正在学习教程,但我不明白的是函数 onCountryChange() 当我执行 setCountry(countryCode) 时 selected 国家/地区的名称出现了。每件事都有效,但如何?由于 countryCode 设置为 event.target.value 并且 value 只不过是特定国家/地区的两个字符代码。那么当我传递的只是两个字母的国家代码时,setCountry 如何将 country 设置为国家的全名。

当您设置 Select 选项的 value 属性时,它将 select 具有相同值的匹配选项。

MenuItem值设置在这里:

<MenuItem value={country.value}>{country.name}</MenuItem>

值和 country 状态确实只采用国家/地区缩写 - 但是一旦匹配选项为 selected,元素的文本内容为 country.name,它给出了国家的全名。