useState在组件卸载时未定义



卸载组件时,connectionId.stop();产生TypeError: Cannot read properties of undefined (reading 'stop'),但connection.stop();停止连接。我怀疑当组件卸载时,useState不再存在,但var connection仍然存在,就在它卸载之前。

我的意思是,如果我从这个组件的子组件调用connectionId.stop();,它会停止连接。

我可以只是使用var connection,但这似乎不是ReactJs做事情的方式?

const [connectionId, setConnectionId] = useState();
useEffect(() => {
var connection;
const fetchJoinedMessage = async () => {
try {
connection = new HubConnectionBuilder()
.withUrl("https://localhost:4581/chat")
.configureLogging(LogLevel.Information)
.build();
await connection.start();
setConnectionId(connection)
} catch (err) {
console.log(err.message)
}
}
fetchJoinedMessage()
return () => {
console.log("Component unmounted")
console.log(connection) // displays the connection
console.log(connectionId) // connectionId undefined
//connection.stop(); // connection is stopped
connectionId.stop(); // connection not stopped
}
}, [])

谢谢

如果您只需要在卸载时使用connectionId来停止它,那么就可以像在连接时那样声明它,考虑使用let而不是var

最新更新