我刚刚开始学习反应。 我有一个组件,它正在调用天气 API 并为用户提供的位置获取数据,用户输入正在 userLoc 下更新,但不知何故,finalLoc 的状态没有更新,每当我控制台记录它时,它都显示 undefined< /strong>。
const Inputs = props => {
const [userLocation, setUserLocation] = React.useState('')
const [finalLocation, setFinalLocation] = React.useState('')
function fetchLocation(e) {
setUserLocation (e.target.value)
}
function fetchDetails(e) {
e.preventDefault()
let baseURL = '//api.openweathermap.org/data/2.5/weather?q='
const API_KEY = '&API_KEY'
let total = baseURL + userLocation + API_KEY
console.log(userLocation) // Outputs the input value
setFinalLocation(userLocation)
console.log(finalLocation) // Comes as blank
console.log(total);
}
return (
<div className='inputs'>
<p className="label">Enter the location to find the weather.</p>
<input type="text" className='loc-input' autoFocus placeholder='Enter a location' name="" id="location" onChange={fetchLocation} value={loc.userLoc || ""} />
<button onClick={fetchDetails}>Get Details</button>
<Outputs loc={loc.finalLoc} results={loc.result} />
</div>
)
}
答案 0 :(得分:1)
const Inputs = props => {
const [finalLoc, setFinalLoc] = React.useState("");
const [userLoc, setUserLoc] = React.useState("");
const [data, setData] = React.useState([]);
function fetchLocation(e) {
userLoc( e.target.value )
}
function fetchDetails(e) {
let baseURL = '//api.openweathermap.org/data/2.5/weather?q='
let API_KEY = '&appid=API_KEY'
let total = baseURL + loc.userLoc + API_KEY
setFinalLoc( userLoc )
fetch(total)
.then(response => response.json())
.then(data => {
setData( data )
})
}
return (
<div className='inputs'>
<p className="label">Enter the location to find the weather.</p>
<input type="text" className='loc-input' autoFocus placeholder='Enter a location' name="" id="location" onChange={fetchLocation} value={ userLoc || ""} />
<button onClick={fetchDetails}>Get Details</button>
<Outputs loc={ finalLoc} results={data} />
</div>
)
}
答案 1 :(得分:0)
如果你在使用 useState 时更新状态,你不会把它写成
setState({state: //data})
但是
setState(//data)
useState 中的更新方法类似于类组件的 setState 方法,但您必须对其进行不同的更新。
查看有关 useState here 的更多信息。
如果你的状态是一个对象,你应该将它更新为一个对象:
const [state, setState] = useState({
name: "John",
lastName: "Due",
});
setState({
name: "Liam",
lastName: "call",
});
顺便说一句,
如果您要更新状态中的多个值,则应在一个函数中更新它。#1
注意: 每次您更新状态时,都会引起 React 重新渲染并减慢您的应用程序的速度。 为了获得更好的性能,您应该始终尝试尽可能少地重新渲染您的应用。
编辑:
#1 如果你的状态是一个对象,你应该在一个函数中更新它。
答案 2 :(得分:0)
您可以使用函数形式。该函数将接收先前的值,并返回一个更新的值。所以要更新状态,我们必须用更新的值复制以前的值,然后用更新的值设置状态
setLoc((loc) => ({ ...loc, finalLoc: loc.userLoc }));
获得结果数据时相同,保留先前状态的副本
setLoc((loc) => ({ ...loc, result: data }));