用Rails和React搭建一个聊天应用,尝试实现ActionCable的实时更新。应用建好后,用setInterval进行消息传递。控制台错误是'Uncaught ReferenceError: App is not defined"。这段代码在我的message_list.jsx容器里面,特别是导致应用程序崩溃。如果能得到任何帮助,我们将非常感激。
componentDidMount() { // For the first channel
this.subscribeActionCable(this.props);
}
subscribeActionCable = (props) => {
App[`channel_${props.selectedChannel}`] = App.cable.subscriptions.create(
{ channel: 'ChannelsChannel', name: props.selectedChannel },
{
received: (message) => {
if (message.channel === props.selectedChannel) {
props.appendMessage(message);
}
}
}
);
}
我能够解决这个问题,想把这个问题记录下来,供其他人参考。我使用 rails6 + webpacker 与 react 和 action cable 来制作一个聊天应用。整个react前端都在assets管道之外的 "javascript "文件夹中。你可能使用了setInterval来刷新消息,而你现在在设置action cable时出现了问题。如果你已经正确配置了其他一切,并且你得到了一个控制台错误,其中 "App is not defined "和消息没有加载,这可能会有帮助。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Rails React Chat</title>
<%= csrf_meta_tags %>
<%= action_cable_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= stylesheet_pack_tag 'application', media: 'all' %> <!-- Uncomment if you import CSS in app/javascript/packs/application.js -->
</head>
<body>
<%= render 'shared/navbar' %>
<%= render 'shared/flashes' %>
<%= yield %>
<%= javascript_include_tag 'application' %>
<%= javascript_pack_tag 'application' %>
<%= yield :after_js %>
</body>
</html>
//= require rails-ujs
//= require_tree .
和cable.js
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree .
(function() {
this.App || (this.App = {});
App.cable = ActionCable.createConsumer();
}).call(this);
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css