onChange 不适用于文本字段中的第一个输入
onChange 事件不会返回文本输入的第一个更改,但适用于后续更改。抱歉,如果这很明显,我是 React 新手。
import React, { useState } from 'react';
import axios from 'axios';
function Header() {
const [text, setText] = useState("");
const [location, setLocation] = useState("");
function handleChange(event) {
setText(event.target.value);
}
// when submit button clicked, current state of the text input is stored inside location constant
function handleClick() {
setLocation(text);
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + location + "&limit=5&appid={apikey}"
function getCoordinates(url) {
axios.get(url).then((response) => {
const locationLat = response.data[0].lat;
const locationLon = response.data[0].lon;
});
}
getCoordinates(geoCoderURL);
}
return (
<div>
<h1>Five Day Forecast</h1>
<input onChange={handleChange} type="text" name="name"autoFocus placeholder="Enter location here."/>
<button type="submit" onClick={handleClick}>Forecast</button>
</div>
)
}
export default Header;
onChange event doesn't return the first change of the text input but works on subsequent changes. Sorry if this is obvious, I'm new to React.
import React, { useState } from 'react';
import axios from 'axios';
function Header() {
const [text, setText] = useState("");
const [location, setLocation] = useState("");
function handleChange(event) {
setText(event.target.value);
}
// when submit button clicked, current state of the text input is stored inside location constant
function handleClick() {
setLocation(text);
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + location + "&limit=5&appid={apikey}"
function getCoordinates(url) {
axios.get(url).then((response) => {
const locationLat = response.data[0].lat;
const locationLon = response.data[0].lon;
});
}
getCoordinates(geoCoderURL);
}
return (
<div>
<h1>Five Day Forecast</h1>
<input onChange={handleChange} type="text" name="name"autoFocus placeholder="Enter location here."/>
<button type="submit" onClick={handleClick}>Forecast</button>
</div>
)
}
export default Header;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您调用
setLocation(text);
时,handleClick
将在location
值实际更新之前完成执行。不需要
location
和setLocation
;看起来也许location
应该与text
相同。When you call
setLocation(text);
,handleClick
will finish execution before thelocation
value is actually updated.There is no need for
location
andsetLocation
; looks like maybelocation
is supposed to be the same astext
.