javascript - 为什么执行函数时useState不是更新状态
问题描述
我试图理解这个问题。为什么只有当我再次单击时,州(在这种情况下为国家)才在执行功能后才更新 setCountry?在这个例子中,当我选择一个国家,然后在第一个 console.log 的函数 addCountry() 中单击 Add Country to state 时,它运行良好并显示当前选择的国家,但第二个带有国家状态的 console.log 显示的是前一个。当然,当 {country} 作为回报时,显然是在显示当前情况。所以我的问题是我应该用什么来正确更新第二个console.log中的国家?
import React, { useState} from "react";
const Country = () => {
const [country, setCountry] = useState([]);
const countries = ["Poland", "England", "Germany", "USA"];
const showCountries = countries.map((country) => <option>{country}</option>);
const addCountry = () => {
const selectCountry = document.getElementById("selectCountry").value;
console.log(selectCountry); //There is current country
setCountry(selectCountry);
console.log(country); //There is previous country
};
return (
<>
<select id="selectCountry">{showCountries}</select>
<button onClick={addCountry}>Add Country</button>
<div>{country}</div>
</>
);
};
export default Country;
解决方案
推荐阅读
- javascript - 将类添加到香草JS中滚动的特定元素
- git - git - 有没有办法让我真正区分 2 个分支?
- javascript - 无法将 onclick 事件添加到 DOM 元素
- ruby-on-rails - 在 Rails 中设置一个额外的记录器——如何只实例化一次?
- regex - 如何用逗号替换文本 [Linux on Windows]
- php - 为什么我的 HTML 正文在我的 PHP 标头中?
- java - 无论字符大小如何生成制表符缩进数组
- php - 传单地图未填写区域
- reactjs - 为什么我的请求使用 Axios 将帖子转为选项?
- javascript - 反转游戏方向