简体   繁体   English

在React Native中延迟setState

[英]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. 所以我使用了react-native-pull-to-refresh组件。 Here in that documentation, it has mentioned that _refresh has been set to 2000 delay. 在该文档的此处,已提到_refresh已设置为2000 delay。

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

But I want to re-render the screen after 2000 delay. 但我想在2000年延迟后重新渲染屏幕。

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. 现在,当我向下拉屏幕时,它不会停留2秒钟(刷新动画也不会停留2秒钟),而是立即隐藏并刷新UI。

Problem 问题

What am I missing here? 我在这里想念什么? How can I keep the refreshing animation for 2 seconds and then call the functions this.updateUI(); 我如何保持刷新动画2秒钟,然后调用函数this.updateUI(); and this.setState({ refreshing: true }); 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: 从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. 看来您可能正在解决Promise,然后尝试做更多的事情...在调用更新函数之前,Promise应该不会解决。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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