reactjs - 如何修复 WebApp 保持渲染状态?
问题描述
我正在使用 React 和 Hooks 设置一个简单的天气应用程序。但是,我发现该应用程序一直在获取 API。我怎样才能阻止这个?
function WeatherInfo (props) {
const [wind,setWind] = useState(undefined);
const [precipitation,setPrecipitation] = useState(undefined);
const [humidity,setHumidity] = useState(undefined);
const [pressure,setPressure] = useState(undefined);
if (props.city) {
useEffect(() => {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();}
).then(data => setWind(data.wind.speed))
})
useEffect(() => {
fetch(`https://api.worldweatheronline.com/premium/v1/weather.ashx?key=a5bf94fc16c84928acb114156182311&q=${props.city}&num_of_days=1&tp=24&format=json`).then(results => {return results.json();}
).then(data => setPrecipitation(data.data.weather[0].hourly[0].chanceofrain))
})
useEffect(() => {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();}
).then(data => setPressure(data.main.pressure))
})
useEffect(() => {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();}
).then(data => setHumidity(data.main.humidity))
})
}
return (
<div>
{props.city &&
<div>
<p>Wind of {props.city} is {wind}</p>
<p>Chance of rain of {props.city} is {precipitation}%</p>
<p>Humidity of {props.city} is {humidity}</p>
<p>Pressure of {props.city} is {pressure}</p>
</div>
}
</div>
)
}
export default WeatherInfo;
预期结果:函数只获取一次 API
解决方案
默认情况下,useEffect
钩子在每次重新渲染时运行。如果您不希望这样,您可以指定第二个可选参数,请参阅https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects。
在您的特定情况下:您可能只想在城市更改时执行效果,所以:
useEffect(/* callbacks as before */, [props.city])
.
此外,您应该只在顶层调用钩子(即不在 ifs 中):https ://reactjs.org/docs/hooks-overview.html#%EF%B8%8F-rules-of-hooks 。您可以将 if 分支移动到 useEffect 的回调中
推荐阅读
- php - 使用数组填充动态下拉列表
- r - swagger codegen R客户端数据模型结构
- angular - 声明、TypeScript 类之后缺少或没有立即执行函数实现
- excel - Excel VBA 每个循环有四个,带有相关的下拉列表
- codefluent - MyPivoRunner 和进度条控件
- c# - EF 2.1 + Npgsql + ExecuteSqlCommand = "$1" 或附近的语法错误
- php - 如何禁止返回状态未见的评论?
- powerbi - Power BI - 簇状柱形图 - 年份百分比
- java - 没有为参数 [io.vertx.ext.unit.TestContext arg0] 注册 ParameterResolver
- android - android闪屏中挂起功能的使用