我正在使用一个伴随的React Native应用程序来配合我的RoR webapp,并希望使用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的经验的人都可以帮助我吗?
答案 0 :(得分:1)
您附加的网址端点不是websocket,因此可能是您的问题。他们列出的The example app仅在2个月前更新,并且基于RN 0.48.3,所以我猜它可能仍然有用。您是否尝试过克隆并运行它?
您似乎也需要设置提供商(&lt; ActionCableProvider&gt;)
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>
);
}
}