问题描述
我试图在名为 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);
});
}
}