React组件在react-pull-to-refresh上失败

问题描述

我有一个带有React前端的相当简单的ASP.NET网站。它具有一个组件MetaWeatherForecast,该组件可从API端点获取一些数据并将其显示在表中。很好。

react-pull-to-refresh引入项目并将其附加到组件后,该表最初会在第一次加载时加载并获取数据,但是一旦我拉动表进行刷新,就会失败。

以下是该组件的修剪后版本,其当前形式为:

MetaWeatherForecast.js

import React,{ Component } from 'react';
import authService from './api-authorization/AuthorizeService'
import Moment from 'moment';
import ReactPullToRefresh from 'react-pull-to-refresh'

export class MetaWeatherForecast extends Component {

    static displayName = MetaWeatherForecast.name;

  constructor(props) {
    super(props);
      this.state = {
          locationForecast: {},loading: true,success: true,errorMessage: null };
  }

  componentDidMount() {
    this.populateWeatherData();
  }

    static renderForecastsTable(locationForecast) {
            // html markup for the table
    }

    static renderError(errorMessage) {
        // error markup
    }

    handleRefresh(resolve,reject) {  

        let success = this.populateWeatherData();

        if (success)
            resolve();
        else
            reject();        
    }

    async populateWeatherData() {

        this.setState({ locationForecast: {},errorMessage: null});

        const token = await authService.getAccesstoken();

        const response = await fetch('api/Metaweatherforecast/GetFiveDayForecast/44544',{
            headers: !token ? {} : { 'Authorization': `Bearer ${token}` }
        });

        const baseResponse = await response.json();

        console.log(baseResponse);

        this.setState({ locationForecast: baseResponse.data,loading: false,success: baseResponse.success,errorMessage: baseResponse.errorMessage });

        return baseResponse.success;
    }

    getContent() {

        let contents;

        if (this.state.loading) {
            contents = <p><em>Fetching forecast...</em></p>
        } else {
            contents = this.state.success
                ? MetaWeatherForecast.renderForecastsTable(this.state.locationForecast)
                : MetaWeatherForecast.renderError(this.state.errorMessage);
        }

        return contents;
    }

  render() {   

      return (
          <ReactPullToRefresh
              onRefresh={this.handleRefresh}
              style={{
                  textAlign: 'center'
              }}>                
              <div>
                <p><em>Pull down to refresh</em></p>
                <h1 id="tabelLabel" >Meta Weather forecast</h1>
                  {this.getContent()}
              </div>
          </ReactPullToRefresh>
        );
    }
};

拉表后引发的错误如下,并在handleRefresh()方法内部引发:

Uncaught (in promise) TypeError: this.populateWeatherData is not a function

任何想法或建议都将受到欢迎

解决方法

在react类中,您必须在构造函数中绑定this

constructor(props) {
    ...
    this.<method> = this.<method>.bind(this);
}

我喜欢使用this library