React State更新异步问题
我有一个为表创建行数据的组件。它设置状态。它还为行状态之一创建一个按钮,其中包含对函数的引用。我希望该按钮可以使用该状态。但这是落后的一项要求。 showJourneyDetails 函数中可用的状态始终是当前状态的前一个状态。我知道反应状态是异步的,那么如何使当前状态在 showJourneyDetails 函数中可用?
const [suspected, setSuspectedData] = useState([]);
const [suspectedReads, setSuspectedReads] = useState(false);
const findVehiclesOfInterestBetweenDateRange = () => {
fetch(`http://127.0.0.1:8000/vehicles`)
.then((response) => response.json())
.then((vehicles) => {
const suspectedDataReads = vehicles.map((row) => {
return {
journey_id: row.journey_id,
reads: row.reads,
};
});
setSuspectedReads(suspectedDataReads);
const suspected = vehicles.map((row) => {
return {
vrm: row.vrm,
start_time: row.start_time,
end_time: row.end_time,
journey_size: row.journey_size,
journey_time: row.journey_time,
score: row.score,
details: (<Button
variant="contained"
onClick={showJourneyDetails}
id={row.journey_id}
>
Details
</Button>),
};
});
setSuspectedData(suspected);
})
.catch((error) => {
console.log(error);
});
};
const showJourneyDetails = (event) => {
console.log(event.target.id);
console.log("showJourneyDetails suspectedDataReads:", suspectedDataReads);
}
I have this component which creates row data for a table. It sets state. It also creates a button for one of the row states, which contains a reference to a function. I want the state to be available to that button. But it is one request behind. The state available in the showJourneyDetails function is always the previous state to the current state. I know react state is asynchronous so how do I make the current state available inside the showJourneyDetails function?
const [suspected, setSuspectedData] = useState([]);
const [suspectedReads, setSuspectedReads] = useState(false);
const findVehiclesOfInterestBetweenDateRange = () => {
fetch(`http://127.0.0.1:8000/vehicles`)
.then((response) => response.json())
.then((vehicles) => {
const suspectedDataReads = vehicles.map((row) => {
return {
journey_id: row.journey_id,
reads: row.reads,
};
});
setSuspectedReads(suspectedDataReads);
const suspected = vehicles.map((row) => {
return {
vrm: row.vrm,
start_time: row.start_time,
end_time: row.end_time,
journey_size: row.journey_size,
journey_time: row.journey_time,
score: row.score,
details: (<Button
variant="contained"
onClick={showJourneyDetails}
id={row.journey_id}
>
Details
</Button>),
};
});
setSuspectedData(suspected);
})
.catch((error) => {
console.log(error);
});
};
const showJourneyDetails = (event) => {
console.log(event.target.id);
console.log("showJourneyDetails suspectedDataReads:", suspectedDataReads);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论