简体   繁体   中英

Delay setState in React Native

Here in my application, it has a pull to refresh component. So I used react-native-pull-to-refresh component. Here in that documentation, it has mentioned that _refresh has been set to 2000 delay.

_refresh: function() {
return new Promise((resolve) => {
  setTimeout(()=>{resolve()}, 2000)
});

But I want to re-render the screen after 2000 delay.

What I came up with

_refresh(context) {
let promise = new Promise((resolve) => {
  setTimeout(() => {
    resolve()
  }, 2000);
  setTimeout(() => {
     this.updateUI();
     this.setState({ refreshing: true });
 }, 2000);
})

return promise
}

Now when I pull the screen down, it does not stay for 2 seconds (Refreshing animation does not stay for 2 seconds) but immediately hide and refresh the UI.

Problem

What am I missing here? How can I keep the refreshing animation for 2 seconds and then call the functions this.updateUI(); and this.setState({ refreshing: true });

Try doing something like this:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve();
    reject(new Error("Error!"));
  }, 2000);
promise.then(() => {
  setTimeout(() => {
     this.updateUI();
     this.setState({ refreshing: true });
  }, 2000);
})

From the example in the github:

_refresh () {
    // you must return Promise everytime
    return new Promise((resolve) => {
      setTimeout(()=>{
        // some refresh process should come here
        this.setState({cards: this.state.cards.concat([this.state.cards.length + 1])})
        resolve(); 
      }, 2000)
    })
  }

It seems you might be resolving the promise and then trying to do more... the promise should not resolve until the updating functions have been called. So I would try something like this:

_refresh(context) {
  let promise = new Promise((resolve) => {
    setTimeout(() => {
      this.updateUI();
      this.setState({ refreshing: true });
      resolve()
    }, 2000);
  })
  return promise
}

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