首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails ActionCable和React本机

Rails ActionCable和React本机
EN

Stack Overflow用户
提问于 2017-11-24 16:56:18
回答 1查看 2.4K关注 0票数 1

我正在开发一个伴随我的RoR webapp的同伴React本地应用程序,并希望使用ActionCable (websockets)构建一个聊天功能。我无法让我的与ActionCable对话。

我尝试过一些库,包括反应-本机动作电缆,但没有成功。最初的连接似乎是有效的(我知道这一点,因为我以前有错误,当我通过适当的params时,它们就消失了)。

这是“我的React本机代码”的缩写版本:

代码语言:javascript
复制
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反应本地,并能帮助我?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-25 06:04:15

您要附加到的url端点不是websocket,所以这可能是您的问题。他们列出的示例应用程序在两个月前刚刚更新,是基于RN0.48.3的,所以我不得不猜测它可能仍然有效。你试过克隆和运行它吗?

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

代码语言:javascript
复制
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>
    );
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47477438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档