gpt4 book ai didi

javascript - 重新渲染次数过多

转载 作者:行者123 更新时间:2023-11-28 17:00:55 25 4
gpt4 key购买 nike

我收到多次重新渲染错误

我尝试使用 useEffect 仅在天气变化时渲染

function DashboardHeaderContent({ looks, weather }) {
const [seasonRange, setSeasonRange] = React.useState();

function renderLook(look) {
return <Look id={look._id} img={look.img} title={look.title} />;
}

if (weather.temp >= 7 && weather.temp <= 16) {
setSeasonRange("Spring");
} else if (weather.temp >= 16 && weather.temp <= 50) {
setSeasonRange("Sommer");
} else if (weather.temp >= 6 && weather.temp <= 18) {
setSeasonRange("Fall");
} else if (weather.temp <= 7) {
setSeasonRange("Winter");
}

状态应该根据weather.temp设置

最佳答案

您可以使用 useEffect() 并使用空数组作为第二个参数,以防止它观察任何状态。所以它基本上只会运行一次。

function DashboardHeaderContent({ looks, weather }) {
const [seasonRange, setSeasonRange] = React.useState();

function renderLook(look) {
return <Look id={look._id} img={look.img} title={look.title} />;
}

useEffect(() => {
if (weather.temp >= 7 && weather.temp <= 16) {
setSeasonRange("Spring");
} else if (weather.temp >= 16 && weather.temp <= 50) {
setSeasonRange("Sommer");
} else if (weather.temp >= 6 && weather.temp <= 18) {
setSeasonRange("Fall");
} else if (weather.temp <= 7) {
setSeasonRange("Winter");
}
}, []);

关于javascript - 重新渲染次数过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com