【问题标题】:Rails ActionCable and React NativeRails ActionCable 和 React Native
【发布时间】:2017-11-24 16:56:18
【问题描述】:

我正在开发一个配套的 React Native 应用程序来配合我的 RoR web 应用程序,并希望使用 ActionCable (websockets) 构建一个聊天功能。我无法让我的 React Native 应用程序与 ActionCable 通信。

我尝试了许多库,包括react-native-actioncable,但都没有运气。最初的连接似乎正在工作(我知道这一点是因为我之前遇到过错误,当我通过正确的参数时它们已经消失了)。

这是我的 React Native 代码的缩写版本:

import ActionCable from 'react-native-actioncable'

class Secured extends Component {
  componentWillMount () {
    var url = 'https://x.herokuapp.com/cable/?authToken=' + this.props.token + '&client=' + this.props.client + '&uid=' + this.props.uid + '&expiry=' + this.props.expiry
    const cable = ActionCable.createConsumer(url)

    cable.subscriptions.create('inbox_channel_1', {
      received: function (data) {
        console.log(data)
      }
    })
  }

  render () {
    return (
      <View style={styles.container}>
        <TabBarNavigation/>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    email: state.auth.email,
    org_id: state.auth.org_id,
    token: state.auth.token,
    client: state.auth.client,
    uid: state.auth.uid,
    expiry: state.auth.expiry
  }
}

export default connect(mapStateToProps, { })(Secured)

任何有更多将 ActionCable 连接到 React Native 经验的人可以帮助我吗?

【问题讨论】:

标签: react-native websocket actioncable


【解决方案1】:

您附加到的 url 端点不是 websocket,所以这可能是您的问题。他们列出的The example app 仅在 2 个月前更新,并且基于 RN 0.48.3,所以我不得不猜测它可能仍然有效。您是否尝试过克隆并运行它?

看起来您还需要设置提供程序 ()

import RNActionCable from 'react-native-actioncable';
import ActionCableProvider, { ActionCable } from 'react-actioncable-provider';

const cable = RNActionCable.createConsumer('ws://localhost:3000/cable');

class App extends Component {
    state = {
        messages: []
    }

    onReceived = (data) => {
        this.setState({
            messages: [
                data.message,
                ...this.state.messages
            ]
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <ActionCable channel={{channel: 'MessageChannel'}} onReceived={this.onReceived} />
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <View>
            <Text>There are {this.state.messages.length} messages.</Text>
        </View>
        {this.state.messages.map((message, index) =>
            <View key={index} style={styles.message}>
                <Text style={styles.instructions}>
                  {message}
                </Text>
              </View>
          )}
      </View>
      )
    }
}

export default class TestRNActionCable extends Component {
  render() {
    return (
        <ActionCableProvider cable={cable}>
          <App />
         </ActionCableProvider>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多