Javascript React组件在React pull刷新时失败
我有一个相当简单的ASP.NET站点,带有react前端。它有一个组件Javascript React组件在React pull刷新时失败,javascript,reactjs,asp.net-core-mvc,pull-to-refresh,Javascript,Reactjs,Asp.net Core Mvc,Pull To Refresh,我有一个相当简单的ASP.NET站点,带有react前端。它有一个组件MetaWeatherForecast,它从API端点获取一些数据并将其显示在表中。那很好 在拉入项目并将其附加到组件之后,表最初会在第一次加载时加载并获取数据,但在我拉入表进行刷新时就会失败 以下是组件当前形式的修剪版本: MetaWeatherForecast.js import React, { Component } from 'react'; import authService from './api-author
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>
);
}
};
在react类中,任何想法或建议都是最受欢迎的,您必须在构造函数中绑定此
constructor(props) {
...
this.<method> = this.<method>.bind(this);
}
构造函数(道具){
...
这个;
}
我喜欢使用。需要绑定的react中的方法。在您的构造函数中,尝试
this.populateWeatherData=this.populateWeatherData.bind(this)
和this.handleRefresh=this.handleRefresh.bind(this)
这真是太神奇了@TKoL成功了!如果你把它写在答案里,我会把它标为解决方案。谢谢
constructor(props) {
...
this.<method> = this.<method>.bind(this);
}