FlatList 的 renderItem 无法识别 "this" 关键字

FlatList's renderItem doesn't recognise "this" keyword

所以,我最近开始在我正在开发的应用程序中重复使用 FlatList。我现在正在一个屏幕上工作,该屏幕提供请求列表并在接受请求后更新,这是通过按下按钮完成的。我正在使用一种名为 getNewRequests 的方法来更新请求,但它似乎无法被 flatline 调用,因为它仅 returns 错误 TypeError: _this3 is undefined.

我真的需要那个方法来工作,因为我需要更新那个屏幕的状态,并且试图在那里输入整个方法,但 returns 同样的错误。在这种情况下,this 总是 returns undefined.

render(){
    return(
      <View style={GenericStyles.styles.genericContainer}>
        <Text> REQUEST SCREEN </Text>

        <FlatList
          data={this.state.requestList}
          renderItem={this.renderItem}
          keyExtractor={item => item.id}
          />

        <Button title="Voltar" color="cyan" onPress={() => this.props.navigation.goBack()}/>
      </View>
    );
  }

renderItem({item}){
    return(
      <Card
        containerStyle={{flex: 1, width: 200}}
        title={item.Username}>
          <Button color="blue" title="Accept" onPress={() => RequestService.allowRequest(item.id, (response) => {
            let rsp = JSON.parse(response);

            if(rsp.success){
              this.getNewRequests();
            }

          })}/>
      </Card>
    );
  }

您需要在构造函数中(或任何您想要的地方)绑定函数:

constructor(props){
    super(props)
    this.renderItem.bind(this)
}

或者使用箭头函数:

renderItem = ({item}) => {
    //your function
}

这样做将使函数可以访问当前组件的this