gpt4 book ai didi

javascript - 如何在没有中央服务器的情况下连接 Gun 来更新所有 React 客户端?

转载 作者:行者123 更新时间:2023-12-03 09:08:51 25 4
gpt4 key购买 nike

这是一个同步 <input> 的基本代码笔的链接带有 Gun 实例的标签,并将 Gun 更新连接到 React setState。
https://codepen.io/anon/pen/weJxNO?editors=0011

我的期望:
当您在多个窗口中打开该程序时,您可以在一个窗口中键入内容并在其他窗口中查看更新。在一个窗口中键入内容会更改 Gun 存储,然后导致所有实例传播事件,从而跨窗口重新渲染所有 React 组件。

实际发生的情况:
如果您在多个窗口中打开该程序,请注意在一个窗口中键入内容会更改所有窗口的 localStorage 值。然而,只有您实际输入的窗 Eloquent 会注册来自 Gun 商店的事件。

可能的解决方案:
我知道我可以在所有客户端都与之通信的服务器上设置一个 Gun 实例。但这不是与Gun的目的背道而驰吗? p2p 系统的优点是您不需要需要中央权威来源。

问题重述:
如何连接程序以便所有 Gun 实例触发更改事件,从而在没有中央服务器的情况下跨窗口更新每个 React 组件?

Codepen 的相关代码:

class App extends React.Component {
constructor() {
super()
this.state = {name: ''};
this.gun = Gun()
}

componentDidMount() {
this.gun.get('user').on(
({ name }) =>
this.setState({ name }))
}
render() {
return <div>
<h1>Hey, {this.state.name || '(your name here)'}</h1>
<input
value={this.state.name}
placeholder="edit your name here"
onChange={({ target }) =>
this.gun.get('user')
.put({ name: target.value })}
/>
<p>you should see updates in multiple browser windows</p>
<p>you can see your localStorgae update every time you type in other windows</p>
<p>but the state is only set when you type in this window</p>
</div>
}
}

最佳答案

虽然 WebRTC 仍然需要信令服务器,但不幸的是浏览器(不是 GUN)仍然需要 1+ 个中继对等点。

可以在非浏览器对等点上使用 GUN 进行 P2P 更新,而无需中央服务器。浏览器的 P2P 能力有限,这不是 GUN 的错。

关于javascript - 如何在没有中央服务器的情况下连接 Gun 来更新所有 React 客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641259/

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