Reactjs 为什么我会得到状态的先前值?
我正在尝试在名为onChange的eventhandler中调用一个服务调用,该调用在select中更改了值。但是在我的事件处理程序中,要么我得到了state的前一个值,要么我的state没有得到更新 这可能是什么原因造成的 我如何处理状态的变化,使其提供更新的值 这是我的组件Reactjs 为什么我会得到状态的先前值?,reactjs,express,react-hooks,react-state,Reactjs,Express,React Hooks,React State,我正在尝试在名为onChange的eventhandler中调用一个服务调用,该调用在select中更改了值。但是在我的事件处理程序中,要么我得到了state的前一个值,要么我的state没有得到更新 这可能是什么原因造成的 我如何处理状态的变化,使其提供更新的值 这是我的组件 function CountryDataAra65(props){ const [countryOption, setCountry] = useState("Select a country");
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>
选择一个国家
{
道具.数据.地图((项目,关键)=>{
返回(
{item}
)
})
}
React挂钩(开箱即用)不是异步的。因此,调用await setCountry
没有任何作用。其次,如果您想在onuntryselected
方法中使用countryOption
的更新值,只需使用e.target.value
中的值即可
功能CountryDataAra65(道具){
const[countryOption,setCountry]=useState(“选择一个国家”);
const[countryData,setCountryData]=useState([]);
var卡体;
//表的标记
const PPTag=“购买力”;
const CLTag=“生活费”;
const HCTag=“卫生保健”;
const CRTag=“犯罪指数”;
const PLTag=“污染指数”;
const QLTag=“生活质量”;
//当选择国家/地区时
//当这个事件处理程序被调用onchangeofselect时,state(countryOption)会给出前面的值
异步函数未选择(e){
const val=e.target.value;
国家/地区(val);
console.log(countryOption);
//以国家为对象
常量国家={
国家:瓦尔,
};
//获取国家数据
//这是服务电话
等待获取国家数据(国家)
。然后((数据)=>{
setCountryData(数据);
控制台日志(数据);
})
.catch((错误)=>{
console.log(错误);
});
}
}
能否请您具体说明从何处获取旧值?谢谢@Dharman,我这样做了,它起作用了,它解决了我的问题,但为什么“状态未立即更新”这篇文章很好地解释了为什么setState不能立即更新的确切原因。事情发生在更新countryOption状态之后。我还尝试在其中使用countryOption状态执行另一个方法,它还为我提供了先前的state值。为什么?好的,谢谢@Fardeen。