为什么我的函数未定义?

时间:2017-10-14 16:57:26

标签: reactjs react-native

TaskQueue: Error with task : undefined is not a function (evaluating 'this._renderReplies(replyCount)')

我上面遇到这个错误。

_renderReplies = (replyCount) => {
    return (<Text>`View ${replyCount} replies`</Text>);
}

_renderItem(row) {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
  }

为什么我得到未定义的函数错误????太奇怪了。

3 个答案:

答案 0 :(得分:3)

您应该将_renderItem功能绑定到class;

使用arrow函数(就像使用_renderReplies一样)将自动绑定它

_renderItem = (row) => {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
  }

或者将其绑定在constructor

constructor(props){
    super(props);
    this._renderItem = this._renderItem.bind(this);
}
_renderItem(row) {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
  }

答案 1 :(得分:2)

_renderItem 无权访问此内容。您可以使用箭头函数或在构造函数中绑定它。箭头功能始终可以访问此功能。

箭头功能方法:

_renderItem = (row) => {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
}

_renderReplies = (replyCount) => {
    return (<Text>`View ${replyCount} replies`</Text>);
}

绑定方法:

constructor(props) {
   this._renderItem = this._renderItem.bind(this)
   this._renderReplies = this._renderReplies.bind(this)
}

_renderItem(row) {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
}

_renderReplies(replyCount) {
    return (<Text>`View ${replyCount} replies`</Text>);
}

答案 2 :(得分:0)

在调用_renderReplies()

时,请尝试不要使用this关键字