【发布时间】:2021-04-02 12:18:37
【问题描述】:
我正在尝试在事件处理程序中调用 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 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>
【问题讨论】:
-
您能否具体说明您从哪里获得旧值?
标签: reactjs express react-hooks react-state