reactjs - 使用 React 钩子时获取最新状态值的正确方法
问题描述
我对 React hooks API 相当陌生,在实现我的应用程序时遇到了 Stale 闭包问题。实现 UseEffect API 以获取最新状态值是可行的,但在事件驱动的流程中,检索最新状态值的最佳方法是什么。有关详细信息,请查看以下代码段 -
该allParticipants
变量使用react-redux useSelector
API 捕获值 -
const allParticipants = useSelector((state) => {
return state.participants;
});
这里注册了一个事件处理程序,以便在触发特定事件时调用 -
async function createPeerConnection(pcIndex) {
console.log(`:: createPeerConnection :: for ${pcIndex}`);
try {
const peerConnection = new RTCPeerConnection(pcConfig);
peerConnection.onnegotiationneeded = (event) => handleNegotiationNeeded(pcIndex, event);
function handleNegotiationNeeded(pcIndex, event) {
console.log(`:: handleNegotiationNeeded for index ${pcIndex}::`);
const requestTo = allParticipants[pcIndex].id
handleNegotiation 函数需要 allParticipants 状态的最新值,该状态在调用该函数之前已更新,但它保存状态的初始值,我认为这是陈旧的闭包问题。我不能在useEffects
这里使用 API,因为触发事件时会调用该函数。这样做的正确方法是什么?
解决方案
推荐阅读
- arrays - 如何从 Node 中的外部函数返回数组
- jquery - 如何在全日历中加载 3rd 方引导程序
- c++ - 从最小堆指针问题合并节点
- google-apps-script - 如何使用刚刚在 Google Apps 脚本中编辑特定列的行的数据发送电子邮件?
- c++ - 在 Visual Studio 2019 C++ 中,如何扩展动态分配的数组以显示其所有元素?
- firebase - Vue项目中纱线更新时出错
- r - 如何只在 gglot 中留下没有空格的列?
- python - Tensorflow 与 Tensorflow Lite 的性能对比
- java - 忽略请求的Wiremock问题,除了一个
- r - 使用 group_by 在行组之间进行划分