如何解决在类中调用react本机函数
我正在以这种方式在应用程序中实现推送器
import Pusher from 'pusher-js/react-native';
Pusher.logToConsole = true;
var pusher = new Pusher('PUSHER_KEY',{
cluster: 'ap1'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event',function(data) {
alert('New order received');
});
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
orderData:[],};
}
componentwillMount(){
this.getorders();
}
async getorders() {
// some code here
}
}
正如您在上面的代码中所看到的,当推动器被触发时,我正在警告alert('New order received');
。但是我不想发出警报,而是希望调用函数getorders()
,但不确定如何执行此操作,因为仅指定getorders()
就无法访问它。
解决方法
代码应写在组件中
Pusher.logToConsole = true;
class Home extends React.Component {
var pusher = new Pusher('PUSHER_KEY',{
cluster: 'ap1'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event',function(data) {
this.getOrders()
});
constructor(props) {
super(props);
this.state = {
orderData:[],};
}
componentWillMount(){
this.getOrders();
}
async getOrders() {
// some code here
}
}
,
因此,我只移动了构造函数中的绑定代码部分,并用getOrders()
调用了this
。
import Pusher from 'pusher-js/react-native';
Pusher.logToConsole = true;
var pusher = new Pusher('PUSHER_KEY',{
cluster: 'ap1'
});
var channel = pusher.subscribe('my-channel');
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
orderData:[],};
channel.bind('my-event',function(data) {
this.getOrders();
});
}
componentWillMount(){
this.getOrders();
}
async getOrders() {
// some code here
}
}
,
您可以按如下所示在订阅中获取并保存订单。
var channel = pusher.subscribe('my-channel');
let self = this;
channel.bind('my-event',function(data) {
//alert('New order received');
self.state.orders= await self.getOrders();
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。