gpt4 book ai didi

javascript - react : how can I force state to update in a functional component?

转载 作者:行者123 更新时间:2023-12-01 16:27:04 25 4
gpt4 key购买 nike

这个功能组件有一个调用onChangeHandler 的模板方法,它接受一个select 值并更新state。问题是,state 直到第二次调用 render 方法后才会更新,这意味着 selected option 的值比 state 值提前了一步 selectedRouteName.

我知道我可以使用类组件中的生命周期方法来强制更新 state,但如果可能的话,我想将其保留为功能组件。

如代码中所述,selectedRouteDirection 的记录状态是所选选项后面的一个值。如何强制 state 更新为功能组件中的正确值?

这个问题与同名问题不同,因为我的问题询问的是我的用例中的实际实现,而不是是否可能。

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('');

//console.log(routes);

const onChangeHandler = event => {

setRouteName({ name: event.target.value });

if(selectedRouteName.name) {
getRouteDirection();
}
}
/*
useEffect(() => {
if(selectedRouteName) {
getRouteDirection();
}
}); */

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 => {
directions = response.ArrayOfTextValuePair.TextValuePair;
// console.log(directions);
setRouteDirection(directions);
})
.catch(error => {
console.log(error);
});

console.log(selectedRouteDirection); // This logged state is one value behind the selected option
}

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

return (
<Fragment>
<select onChange={onChangeHandler}>
{routeOptions}
</select>
</Fragment>
);
};

export default RouteSelect;

最佳答案

嗯,实际上..尽管我仍然认为效果是正确的方法..您的 console.log 位置错误..fetch 是异步的并且您的 console.log 就在 fetch 指令之后。

正如@Bernardo 所述.. setState 也是异步的所以在您调用 getRouteDirection(); 时,selectedRouteName 可能仍具有之前的状态。

所以要在设置状态后触发 getRouteDirection();。您可以使用效果并将 selectedRouteName 作为第二个参数传递(这实际上是一种优化,因此效果仅在 selectedRouteName 发生变化时触发)

所以这应该可以解决问题:

useEffect(() => {
getRouteDirection();
}, [selectedRouteName]);

但是老实说……如果您可以提供 Stackblitz 或类似工具,您可以在其中重现该问题。我们绝对可以为您提供更好的帮助。

关于javascript - react : how can I force state to update in a functional component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257685/

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