gpt4 book ai didi

javascript - React useState 导致渲染循环

转载 作者:行者123 更新时间:2023-12-02 22:20:01 25 4
gpt4 key购买 nike

我正在获取数据并尝试使用 useState Hook 将响应存储在状态中。当我从 getRouteDirection 函数设置 selectedRouteDirection 时,渲染会无限循环运行。如何使用 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()再次,依此类推。

关于javascript - React useState 导致渲染循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59255873/

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