如何调用React Native中组件的render函数内的对象内的类?

时间:2018-01-22 19:19:30

标签: javascript reactjs function react-native

我不确定如何描述我正在尝试用文字做什么,所以请看一下以下代码:

这就是导致我出现问题的原因: this.fetchMessages()

import React, { Component } from 'react';
import { PushNotificationIOS, FlatList, TextInput, ActivityIndicator, ListView, Text, View, Image, TouchableWithoutFeedback, AsyncStorage } from 'react-native';
import { Actions } from 'react-native-router-flux';
import ConversationsItem from './ConversationsItem';
import { conversationFetch } from '../actions';
import { connect } from 'react-redux';
import { Divider } from 'react-native-elements'
import PushNotification from 'react-native-push-notification';

class Conversations extends Component {

  componentDidMount() {
    this.props.conversationFetch()
  }

  fetchMessages() {
    this.props.conversationFetch()
  }

  render() {

    PushNotification.configure({
      onNotification: function(notification) {
        PushNotification.getApplicationIconBadgeNumber((response) => {
            PushNotification.setApplicationIconBadgeNumber(response + 1)
        })

        console.log( 'NOTIFICATION:', notification )
        notification.finish(PushNotificationIOS.FetchResult.NoData);

        this.fetchMessages()

      }
    });

    if (!this.props.email) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    console.log(this.props.conversations)

    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        ...
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  console.log(state)
  const { conversations } = state.conversation;
  const { email } = state.conversation;

  return { conversations, email };
};

export default connect(mapStateToProps, { conversationFetch })(Conversations);

当我在PushNotification.configure({})中调用this.fetchMessages()时,收到以下错误消息:

  

this.fetchMessages不是函数

我不确定我所做的事情是否可行,但如果是的话,我真的很想知道如何做到这一点。

我尝试添加.bind(this)和其他方法,但无论如何都得到了相同的错误。

谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

所以你实际上尝试在构造函数中绑定fetchMessages函数?像这样:

constructor(props) {
 super(props)
 this.fetchMessages = this.fetchMessages.bind(this);
}

您还可以使用箭头函数将方法绑定到类,而无需调用构造函数,如下所示:

() => this.fetchMessages()

答案 1 :(得分:1)

使用function关键字声明的函数有自己的this,因此this函数内的onNotification不会引用该类。

因此使用箭头函数语法,它将在词法上解析this,而this里面的值将引用类本身。所以转换

onNotification: function(notification) { 

onNotification: (notification) => {