【问题标题】:Map functions & continous rerendering with UseEffect使用 UseEffect 进行地图功能和连续重新渲染
【发布时间】:2020-10-21 05:58:11
【问题描述】:

当我在我的 React 应用程序中调用以下代码时,我会收到对“预测”控制台的持续更新。我认为这与我在 zippedforecasts 映射中所做的参考有关?

如何防止“预测”的这种状态变化循环?

function App() {
    const [dailyforecasts, setDailyforecasts] 
    const [hourlyforecasts, setHourlyforecasts
    const [forecasts, setForecasts] = useState

    useEffect(() => {
        axios.get('https://api.openweathermap.
            params: {
                lat: 37.773972,
                lon: -122.431297,
                appid: API_Key,
                units: "imperial",
            }
    })      
            .then(
                res => {
                const newDailyforecasts = res.
                    .map(obj => obj)

                setDailyforecasts(newDailyfore

                const newHourlyforecasts = res
                    .map(obj => obj)

                const current_hour = new Date(
                const day1 = newHourlyforecast
                const day2 = newHourlyforecast
current_hour))) 
                const day3 = newHourlyforecast

                const newHFs = [day1, day2, da


                setHourlyforecasts(newHFs) 
                }
            )},[]);

    const zippedforecasts = dailyforecasts.map
        { 
            return (hourlyforecasts[index]) ?
                ({dailyForecast:day, hourlyFor
                ({dailyForecast:day})
        })      


    useEffect(() => {
        setForecasts(zippedforecasts)
    }, [zippedforecasts])
    console.log(forecasts)

【问题讨论】:

  • 您的代码在特定列大小后被截断。

标签: reactjs setstate use-effect


【解决方案1】:

你不需要第二个 useEffect。 您传递了在每次渲染时创建的 zippedForecast。这就是为什么你最终会陷入无限循环。

只要打电话

 setForecasts(zippedforecasts) 

压缩预测之后

【讨论】:

  • 我的核心问题是,完全按照你的建议去做会给我一个“重新渲染太多”的错误。我已经更新了我的代码,你能再看看吗?
【解决方案2】:

它会导致无限循环,因为每次重新渲染都会重新定义zippedforecasts,这会不断触发第二个useEffect。您可以记住它,以便它只在更改时运行。

    const zippedforecasts = useMemo(() => dailyforecasts.map((dailyForecast) => { 
            return (hourlyforecasts[index]) ?
                ({dailyForecast:day, hourlyFor // this looks to be cut off
                ({dailyForecast:day})
        }), [hourlyforecasts]);    


    useEffect(() => {
        setForecasts(zippedforecasts)
    }, [zippedforecasts])

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 2021-11-26
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2021-10-12
    • 2021-12-30
    相关资源
    最近更新 更多