gpt4 book ai didi

javascript - 浏览器选项卡之间的 Redux 通信使乒乓效应(多路通信)

转载 作者:行者123 更新时间:2023-11-29 18:59:04 25 4
gpt4 key购买 nike

我看到了很多关于如何使用 Redux/JavaScript 与本地存储在选项卡之间通信/共享数据的解决方案。喜欢:

import { applyMiddleware, createStore } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";
import promise from "redux-promise-middleware";

import reducer from "./reducers";
import {sourceId} from "./utils/helper";

const storageKey = 'redux-local-tab-sync';

function wrapAction(action) {
return {
action,
sourceId,
time: Date.now()
}
}

function storageMiddleware() {
return () => next => action => {
const wrappedAction = wrapAction(action);

localStorage.setItem(storageKey, JSON.stringify(wrappedAction));

next(action);
}
}

export function createStorageListener(store) {
return () => {
const wrappedAction = JSON.parse(localStorage.getItem(storageKey));

if (wrappedAction.sourceId !== sourceId) {
console.log(wrappedAction.action)
store.dispatch(wrappedAction.action);
}
}
}

const middleware = applyMiddleware(promise(), thunk, storageMiddleware(), logger());
const store = createStore(reducer, middleware);

window.addEventListener('storage', createStorageListener(store));

export default store;

Javascript: sharing data between tabsCommunication between tabs or windows .

但是我找到的所有解决方案都有一个小问题。它们会产生乒乓效应。因此,当 A 选项卡存储更改时,将设置 B 选项卡存储,因为它从 localstorage 获取消息。但是,由于 B 选项卡存储已更改,因此它会触发之前由 A 选项卡发送的“相同更改事件”(但带有自己的信息)。因此,选项卡的存储将通过本地存储事件发生变化……一切都从头开始。

是否有更好的方法来处理信息同步,其中:
- A 可以向 B [, C, D, ...] 发送消息; B 可以向 A [, C, D, ...] 发送消息;等等
- 不做乒乓球效果,
- 防止无限改变自己的存储。

最佳答案

也许以下会起作用,当从另一个选项卡触发时,它将创建一种特殊类型的操作:

function storageMiddleware() {
return () => next => action => {
if(action.type!=="from other tab"){
const wrappedAction = wrapAction(action);
localStorage.setItem(storageKey, JSON.stringify(wrappedAction));
}else{
action=action.data;
}
next(action);
}
}

export function createStorageListener(store) {
return () => {
const wrappedAction = JSON.parse(localStorage.getItem(storageKey));

if (wrappedAction.sourceId !== sourceId) {
console.log(wrappedAction.action)
store.dispatch({
type:"from other tab",
data:wrappedAction.action
});
}
}
}

关于javascript - 浏览器选项卡之间的 Redux 通信使乒乓效应(多路通信),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47886807/

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