带有 React-native 的推送器订阅,setState 更新

pusher subscription with React-native, setState update

我正在尝试在 React-native 应用程序中使用 Pusher-JS 实现功能,但很难适当地更新此应用程序中变量的状态。

主 class 的外侧,我定义

var pusher = new Pusher('xxxxxxxsome number and code');

在主要 class 组件中,我定义了一个函数

test() {
    var channel = pusher.subscribe('test_channel');
    console.log('ddddddd');
    channel.bind('my_event', function(data) {

    if (data != null) {
      if (data.message != null){
        console.log(data.message);
        this.setState({
          message_box: data.message
          });
      }
    }  
    }.bind(this));
  }

然后我将 test() 放在 render() 函数下,如下所示。

render() {
    this.what();
    ...

当我将短信(从推送测试服务器)推送到 'test_channel'(在移动应用程序中)时,应用程序冻结。当我在 Chrome 控制台中看到登录时,console.log('dddddd') 和 console.log(data.message) 不断快速向下滚动(看起来像 test( ) 被重新渲染了很多 ).

我试图在 render() 之外使用 test() 但我不知道如何在主要组件之外单独放置和更新状态变量。

有什么方法可以稳定此功能或在主要组件 ( this ) 之外设置状态?

请与我分享任何想法!

最佳

您的 test 函数是否在每次渲染时都被调用? Pusher#bind 每当被调用时都会向其注册表添加一个新的回调。可能是每当有消息进来时,这个函数就会被多次调用,导致注册表中的回调更多。

也许尝试绑定一次事件,也许在 getInitialState?