简体   繁体   中英

Pull to Refresh and setState not working - React Native

React Native App
I am implementing Pull to refresh in my Flatlist prop "onRefresh"
onRefresh called the function "refreshcontrol()" see code below.
I need to change my state "refreshing" to true before I fetch from my API. But it throws the maximum update error.

export default class NotificationScreen extends Component {


  constructor(props) {
   super(props)
   this.state = {
      refreshing: false 
    }
  }
.
.
.
.
.
  refreshControl() {
    const { refreshing } = this.state;
    this.setState({ refreshing : true )}.    // throws maximum update error

    return (
      <RefreshControl
        refreshing={refreshing}
        onRefresh={fetchNotifications.bind(this)}      //fetch from API only when refreshing is true
        colors={['#2B70AD']}
      />
    );
  };


}

How else can I set my state to "refreshing: true"??? Help please!!!!

This is how it was fixed. Solution:

refresh = async() => {
    this.setState({refreshing : true})
    try {
      const notifications = await fetchNotifications();
      this.setState({
        notifications,
        error: null,
        refreshing: false
      });
    } catch (error) {
      this.setState({
        notifications: [],
        error,
        refreshing: false
      });
    }
  }

  refreshControl() {
    const { refreshing } = this.state;

    return (
      <RefreshControl
        refreshing={refreshing}
        onRefresh={this.refresh}
        colors={['#2B70AD']}
      />
    );
  };

  refreshFlatlist = () => {
    this.setState(
      {
        refresh: true,
      },
      () => this.getTodosHandler()
    );
    this.setState({
      refresh: false,
    });
  };

This is how I refresh the default state of course is false. the todosHandler always holds the current todos. Its a call to a SQLite DB stored on the phone locally.

Now the flatlist RefreshComponent I used:

   <FlatList
            refreshControl={
              <RefreshControl
                refreshing={this.state.refresh}
                onRefresh={this.refreshFlatlist}
              />
            }
            extraData={this.state.refresh}
            data={this.state.toDoArray}
            keyExtractor={(item, index) => item.id.toString()}
            renderItem={({ item }) => ( ... 

Look into it maybe it will help you - this works for me like a charm;)

This should work perfectly. I think there is a typo in your code. You are using try instead of true. I think that might be the cause of the error.

This might not be the issue but I'll put it here for others (like me) trying to debug:

Make sure that your list is not put inside a ScrollView!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM