我有一个相当简单的ASP.NET站点与一个反应前端。它有一个组件MetaWeatherForecast,它从一个API端点获取一些数据并将其显示在一个表中。效果很好。
在将反应-拉动-刷新导入项目并将其附加到组件后,表最初在第一次加载时加载和获取数据,但在我拉出表刷新后立即失败。
下面是该组件当前形式的修整版本:
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: {}, loading: true, success: true, 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欢迎您提出任何意见或建议。
发布于 2020-08-25 13:58:23
在react类中,必须在构造函数中绑定this。
constructor(props) {
...
this.<method> = this.<method>.bind(this);
}我喜欢使用这个图书馆。
https://stackoverflow.com/questions/63580275
复制相似问题