微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么我得到状态的先前值?

我试图在名为 onChange 的事件处理程序中调用 select 中的值。但是在我的事件处理程序中,要么我获得了 state 的先前值,要么我的 state 没有得到更新。

这可能是什么原因造成的?

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

这是我的组件

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 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 钩子(开箱即用)不是异步的。所以调用 await setCountry 没有任何作用。其次,如果您想在 countryOption 方法中更新 onCountrySelected 的值,您可以简单地使用 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);
      });
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。