React useState导致渲染循环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React useState导致渲染循环相关的知识,希望对你有一定的参考价值。

我正在获取数据,并尝试使用useState挂钩将响应存储为状态。当我从selectedRouteDirection函数设置getRouteDirection时,渲染将在无限循环中运行。如何使用useState设置状态并仅渲染一次?

import React,  useState, Fragment, useEffect  from 'react';

const parser = require('xml-js');

const RouteSelect = props => 
    const  routes  = props;

    const [selectedRouteName, setRouteName] = useState('');
    const [selectedRouteDirection, setRouteDirection] = useState('');

    useEffect(() => 
        if(selectedRouteName) 
            getRouteDirection();
        
    );

    const onChangeHandler = event => 
        setRouteName( name: event.target.value );
    

    const getRouteDirection = () => 

        const filteredRoute = routes.filter(route => route.Description._text === selectedRouteName.name);
        const num = filteredRoute[0].Route._text;

        let directions = [];
        fetch(`https://svc.metrotransit.org/NexTrip/Directions/$num`)
            .then(response =>  
                return response.text();
            ).then(response => 
                return JSON.parse(parser.xml2json(response, compact: true, spaces: 4));
            ).then(response =>  // offending block
                directions = response.ArrayOfTextValuePair.TextValuePair;
                // console.log(directions);
                setRouteDirection(directions);    
            )
            .catch(error => 
                console.log(error);
            );

        console.log(selectedRouteDirection);
    

    const routeOptions = routes.map(route => <option key=route.Route._text>route.Description._text</option>);

    return (
        <Fragment>
            <select onChange=onChangeHandler>
                routeOptions
            </select>
        selectedRouteName ? getRouteDirection() : null 
        </Fragment>
    );
;

export default RouteSelect;
答案

那是因为您要在返回的值中调用getRouteDirection(),而不要使用useEffect来调用getRouteDirection()

 ...

 useEffect(() => getRouteDirection());

 return (
        <Fragment>
            <select onChange=onChangeHandler>
                routeOptions
            </select>
         //some thing 
        </Fragment>
    );

解释:每次调用getRouteDirection()都会改变状态,当状态改变时,这将导致再次调用getRouteDirection(),依此类推。

以上是关于React useState导致渲染循环的主要内容,如果未能解决你的问题,请参考以下文章

React:useState 钩子中的 setState 在啥情况下会导致重新渲染?

React hooks:为啥异步函数中的多个 useState 设置器会导致多次重新渲染?

React 通过使用 useState 的功能变体来防止重新渲染

React.js useState hook 导致过多的重新渲染并且无法更新我的状态

为啥 useState 会导致组件在每次更新时渲染两次?

从组件中的 useState 多次调用 state updater 会导致多次重新渲染