状态更改后调用函数

时间:2019-02-13 02:00:11

标签: react-native

我正在构建一个React Native应用程序,当按下一个按钮时,我想调用两个函数。第一个将进行get调用并设置状态loading: true,第二个将显示带有该get调用结果的弹出窗口。

仅当loading === false时,我才调用第二个函数,但是它会在第一个函数之后立即执行,然后状态才能更改,因为默认情况下加载是false。我可以使用setTimeout解决此问题,但我想知道是否有更干净的方法可以做到这一点。

onPress() {
  this.props.getUsers();
  setTimeout(() => {
    if (this.props.loading === false) {
      this.props.popUpVisible();
    }
  }, 1000);
}

3 个答案:

答案 0 :(得分:1)

您可以为此创建回调函数

-m32

在onPress功能中

getUsers = (callback) => {
  //do whatever you want

  //when it's done
  callback();
}

答案 1 :(得分:0)

使用getDerivedStateFromProps。组件的道具发生更改时,它始终会触发。 下面是示例。

class EmailInput extends Component {
  state = {
    email: this.props.defaultEmail,
    prevPropsUserID: this.props.userID
  };

  static getDerivedStateFromProps(props, state) {
    // Any time the current user changes,
    // Reset any parts of state that are tied to that user.
    // In this simple example, that's just the email.
    if (props.userID !== state.prevPropsUserID) {
      return {
        prevPropsUserID: props.userID,
        email: props.defaultEmail
      };
    }
    return null;
  }

  // ...
}

答案 2 :(得分:0)

setState 函数可以接受两个参数:

setState(更新程序,回调)

setState({loading:true},() => { 
     //this fires once state.loading === true

})