【发布时间】:2020-11-19 12:43:15
【问题描述】:
使用 web socket(@aspnet/signalr) 它工作正常(在组件回调中接收消息)很好,我能够在这个回调中的组件(connection.on(“UpdateProgress”...)中接收和触发回调它的增量计数器是状态变量(numberOfFailed).. 它只触发一次渲染,我设置调试器并看到numberOfFailed 始终为 0。
这里有什么问题?为什么调用setNumberOfFailed 不会改变numberOfFailed 的值。
这里是代码;
const [numberOfFailed, setNumberOfFailed] = useState(0);
const [connection, setConnection] = useState(null);
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl(`${config.API_BASE_URL}update-progress`, {
transport: HttpTransportType.WebSockets,
accessTokenFactory: () => {
return `${localStorage.token}`;
},
})
.build();
setConnection(newConnection);
}, []);
useEffect(() => {
const fetchData = async () => {
if (connection) {
try {
await connection.start();
connection.onclose((error) => {
console.info('Connection Closed:', error);
});
if (connection.state === HubConnectionState.Connected) {
connection.on('UpdateProgress', (message) => {
debugger;
if (message.count) {
setTitleText(`Bildirim Gonderim Başladı, Toplam Alıcı Sayısı:${message.count}`);
} else if (message.status == 1) {
let _t = numberOfFailed + 1;
setNumberOfFailed(_t);
}
console.info('message', message);
});
}
} catch (err) {
console.log(err);
}
}
};
fetchData();
}, [connection]);
【问题讨论】:
标签: reactjs react-hooks