首页 > 解决方案 > 为什么执行函数时useState不是更新状态

问题描述

我试图理解这个问题。为什么只有当我再次单击时,州(在这种情况下为国家)才在执行功能后才更新 setCountry?在这个例子中,当我选择一个国家,然后在第一个 console.log 的函数 addCountry() 中单击 Add Country to state 时,它​​运行良好并显示当前选择的国家,但第二个带有国家状态的 console.log 显示的是前一个。当然,当 {country} 作为回报时,显然是在显示当前情况。所以我的问题是我应该用什么来正确更新第二个console.log中的国家?

import React, { useState} from "react";

const Country = () => {
  const [country, setCountry] = useState([]);

  const countries = ["Poland", "England", "Germany", "USA"];
  const showCountries = countries.map((country) => <option>{country}</option>);
  const addCountry = () => {
    const selectCountry = document.getElementById("selectCountry").value;
    console.log(selectCountry); //There is current country
    setCountry(selectCountry);
    console.log(country); //There is previous country
  };

  return (
    <>
      <select id="selectCountry">{showCountries}</select>
      <button onClick={addCountry}>Add Country</button>
      <div>{country}</div>
    </>
  );
};

export default Country;

标签: javascriptreactjs

解决方案


推荐阅读