gpt4 book ai didi

javascript - 如何在reactJS中管理多选项卡注销?

转载 作者:行者123 更新时间:2023-12-02 00:57:05 24 4
gpt4 key购买 nike

window.addEventListener('storage', e => {
if(e.key === 'access_token' && e.oldValue && !e.newValue) {
store.dispatch(userSignOut());
}
})

如果这是一个合适的解决方案,那么我应该将其粘贴到哪里(生命周期事件)?

最佳答案

最好的方法是使用 BrodcastChannel JavaScript 中的功能。广播 channel API 允许具有相同来源(通常是来自同一站点的页面)的浏览上下文(即窗口、选项卡、框架或 iframe)之间进行简单通信。

例如:

// Connecting to a broadcast channel
const userChannel = new BroadcastChannel('user');

function signOut() {
// and after that, we have to broadcast a message to the user channel which user has signed out from the application as below:
userChannel.postMessage({
userId: "", // If the user opened your app in multi-tabs and signed-in with multi accounts, you need to put the userId here to identify which account has signed out exactly
payload: {
type: "SIGN_OUT"
}
});
}
}

因此,我们创建了用户的 BrodcastChannel,但我们需要观察用户 channel 发送的消息,并根据负载类型执行正确的操作。

userChannel.onmessage = data => { 
if(data.payload.type === "SIGN_OUT") {
// As I talked before about multi-accounts, we need to check the current user id with the sent userId by the userChannel and if they were the same, we have to dispatch the userSignOut action.
store.dispatch(userSignOut());
}
}

关于javascript - 如何在reactJS中管理多选项卡注销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com