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

Adi*_*a V 6 javascript reactjs

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

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

Ali*_*rki 8

最好的方法是使用BrodcastChannelJavascript 中的功能。广播通道 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"
        }
    });
}
}
Run Code Online (Sandbox Code Playgroud)

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

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());
   }
}
Run Code Online (Sandbox Code Playgroud)

  • IE 11 或 safari 浏览器不支持它。 (2认同)