【发布时间】:2020-09-28 02:41:09
【问题描述】:
请原谅我,如果这是漫无目的,我对 Rails 很满意,但 React 对我来说仍然很新。
我有一个新的 Rails 6 应用程序,它使用 ActionCable 和 Webpack 用于 ReactJS 前端,所有这些都包含在应用程序中。
这个安装似乎已经完成了很多使用 @rails/actioncable npm 包将 ActionCable 连接到 ReactJS 的工作。我读过的所有教程似乎都在使用 Rails 5,我认为需要更多的设置才能让事情顺利进行。
我生成了一个GardensChannel,它创建了以下文件。
在 Rails 方面
class GardensChannel < ApplicationCable::Channel
def subscribed
stream_from 'gardens_channel'
end
def received(data)
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
在 ReactJS 方面
import consumer from "./consumer"
consumer.subscriptions.create("GardensChannel", {
connected() {
console.log ('Im connected!')
// Called when the subscription is ready for use on the server
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
console.log(data)
}
});
只有这样,没有其他配置,我可以运行 ActionCable.server.broadcast 'gardens_channel', "TEST!" 并看到 TEST! 在我的 Devtools 控制台中弹出。
我希望做的是使用我已经配置了减速器等的useContext 挂钩连接接收到的数据以更新我的应用程序状态。
我读过的所有 Actioncable/ReactJS 教程似乎都假设了两件事。我正在使用 Redux(我试图避免它,因为它看起来有点矫枉过正)并且我需要 react-actioncable-provider npm 包,但似乎该功能已经得到照顾,因为我已经成功连接到通道和接收数据。所以这些教程的其余部分没有帮助。
您可以查看代码库here。
获取我从频道接收的数据并将其传递给我的 useContext 挂钩的最佳方法是什么?
【问题讨论】:
标签: ruby-on-rails reactjs actioncable