当我尝试在websocket回调中达到该状态时,我没有收到它的最新版本:
import update from 'immutability-helper';
import React, {useCallback, useEffect, useState} from 'react';
const [pendingResponse, setPendingResponse] = useState([]);
const addPendingResponse = (sequence, callback) => {
setPendingResponse(prevPendingResponse => {
return update(prevPendingResponse, {$push:[{sequence: callback}]});
});
};
const wsOnMessage = useCallback((event) => {
const message = event.data;
if (message.payload.response_to in pendingResponse) {
// NOT GETTING THE LATEST pendingRespone STATE !
pendingResponse[message.payload.response_to]();
}
}, [pendingResponse]);
useEffect(() => {
console.log('useEffect');
console.log('setting web socket...');
const ws = new WebSocket('ws://127.0.0.1:8000/chat');
ws.onmessage = wsOnMessage;
}, []);
有什么方法可以在更新状态时强制获取最新状态(使用函数而不是直接分配)?
答案 0 :(得分:1)
当useCallBack的deps更改时,新函数将返回新的引用,因此您必须用新的onmessage函数进行更新。
尝试以下代码:
import update from 'immutability-helper';
import React, { useCallback, useEffect, useState, useRef } from 'react';
const [pendingResponse, setPendingResponse] = useState([]);
const webSocket = useRef(new WebSocket('ws://127.0.0.1:8000/chat'));
const addPendingResponse = (sequence, callback) => {
setPendingResponse(prevPendingResponse => {
return update(prevPendingResponse, { $push: [{ sequence: callback }] });
});
};
const wsOnMessage = useCallback((event) => {
const message = event.data;
if (message.payload.response_to in pendingResponse) {
// NOT GETTING THE LATEST pendingRespone STATE !
pendingResponse[message.payload.response_to]();
}
}, [pendingResponse]);
useEffect(() => {
if (webSocket && webSocket.current) {
webSocket.current.onmessage = wsOnMessage;
}
}, [wsOnMessage]);