为什么我得到的是以前的状态值?

Why am I getting the previous value of state?

我正在尝试在 select 中的值的名为 onChange 的事件处理程序中进行服务调用。但是在我的事件处理程序中,我得到的是以前的状态值,或者我的状态没有得到更新。

可能是什么原因造成的?

我如何处理这种状态变化,以便它为我提供更新后的值?

这是我的组件

function CountryDataAra65(props){

const [countryOption, setCountry] = useState("Select a country");
const [countryData, setCountryData] = useState([]);

var cardBody;

// Tags for table
const PPTag = "Purchasing Power";
const CLTag = "Cost of Living";
const HCTag = "Health Care";
const CRTag = "Crime Index";
const PLTag = "Pollution Index";
const QLTag = "Qualit of Life";

// When a country is selected
// When this event handler is called onChange of select, the state(countryOption) gives me the previous value
async function onCountrySelected(e){
    const val = e.target.value;
    await setCountry(val);

    console.log(countryOption);
    
    // To pass country as object
    const country = {
        "country": countryOption
    }

    // To get country's data
    // This is a service call
    await getCountryData(country)
    .then(data =>{
        setCountryData(data);
        console.log(data);
    })
    .catch(error =>{
        console.log(error);
    })
}

下面是我的select输入


<select className="form-control" aria-label="Default select example"  onChange={onCountrySelected}>
  <option selected>Select a country</option>
  {
    props.data.map((item, key) => {
      return (
        <option defaultValue={item} key={key}>{item}</option>
      )        
    })
  }
</select>

React hooks(开箱即用)不是异步的。所以调用 await setCountry 不会做任何事情。其次,如果你想在 onCountrySelected 方法中更新 countryOption 的值,你可以简单地使用 e.target.value.

中的值
function CountryDataAra65(props) {
  const [countryOption, setCountry] = useState("Select a country");
  const [countryData, setCountryData] = useState([]);

  var cardBody;

  // Tags for table
  const PPTag = "Purchasing Power";
  const CLTag = "Cost of Living";
  const HCTag = "Health Care";
  const CRTag = "Crime Index";
  const PLTag = "Pollution Index";
  const QLTag = "Qualit of Life";

  // When a country is selected
  // When this event handler is called onChange of select, the state(countryOption) gives me the previous value
  async function onCountrySelected(e) {
    const val = e.target.value;
    setCountry(val);

    console.log(countryOption);

    // To pass country as object
    const country = {
      country: val,
    };

    // To get country's data
    // This is a service call
    await getCountryData(country)
      .then((data) => {
        setCountryData(data);
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }
}