首页 > 解决方案 > Ionic IonRefresher 渲染 TypeError 不是函数

问题描述

这是我的代码:

class Calendar extends React.Component<{},State> {
  
  componentDidMount() {
    this.fetchCalendarApi(); //>> Working 
  }
  fetchCalendarApi(){
     //Doing my API call here
  }
  doRefresh(event: CustomEvent<RefresherEventDetail>){
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operation has ended');
      this.fetchCalendarApi(); //>> Not working
      event.detail.complete();
    }, 2000);
  }
 renderCal(){
    return (
      <IonPage>      
        <IonContent>  
          
          <IonRefresher slot="fixed" onIonRefresh={this.doRefresh}>
            <IonRefresherContent></IonRefresherContent>
          </IonRefresher>  
        </IonContent>    
     </IonPage>
    )
  }  
}

当我实际使用 pull refresh 时出现此错误:

TypeError:this.fetchCalendarApi 不是 [...] 的函数

谢谢

标签: reactjsionic-framework

解决方案


您需要将 doRefresh 函数更改为箭头函数:

doRefresh = (event: CustomEvent<RefresherEventDetail>) => {
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operation has ended');
      this.fetchCalendarApi(); //>> Not working
      event.detail.complete();
    }, 2000);
  }

问题是因为您使用的是普通函数,因此无法获取 fetchCalendarApi() 函数,因为它不在范围内。通过使用箭头函数,this 将引用定义方法的类。


推荐阅读