onChange 不适用于文本字段中的第一个输入
onChange not working on the first input into the text field
onChange 事件不会 return 文本输入的第一次更改,但适用于后续更改。对不起,如果这很明显,我是 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;
当您调用 setLocation(text);
时,handleClick
将在 location
值实际更新之前完成执行。
不需要location
和setLocation
;看起来 location
应该与 text
.
相同
function handleClick() {
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + text + "&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);
}
onChange 事件不会 return 文本输入的第一次更改,但适用于后续更改。对不起,如果这很明显,我是 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;
当您调用 setLocation(text);
时,handleClick
将在 location
值实际更新之前完成执行。
不需要location
和setLocation
;看起来 location
应该与 text
.
function handleClick() {
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + text + "&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);
}