简体   繁体   中英

Async render react-native

I've got a qr code scanner and based on the response from the server, i want to show a modal with different back colors!

I used react-native-qrcode-scanner and react-native-modalbox .

App.js:

  render() {
    return (
      <View style={styles.container}>
        <Header headerText="Scan 😁" />

        <View style={styles.cameraContainer}>
          <QRCodeScanner
            ref={node => {
              this.scanner = node;
            }}
            onRead={this.onRead.bind(this)}
            cameraStyle={{ height: "100%" }}
          />
        </View>

        {this.renderModal()}
      </View>
    );
  }

And then we have the onRead() function which is:

onRead(e) {
    // send request to server and receive the response!
    switch (msg from server){
      case "IN": {
        userStatus = "1";
      }

      case "OUT": {
        userStatus = "0";
      }

      case "Error": {
        userStatus = "-1";
      }

    this.refs.myModal.open();
}

and finally the renderModal() :

renderModal() {
    switch (userStatus) {
      case "1": {
        (modalBackgroundColor = "#90EE90"), (modalText = "In");
      }

      case "0": {
        (modalBackgroundColor = "#87CEFA"), (modalText = "Out");
      }

      case "-1": {
        (modalBackgroundColor = "#FF0000"), (modalText = "Error");
      }
    }

    return (
      <Modal
        style={styles.modalStyle}
        position={"center"}
        ref={"myModal"}
        backdropColor={modalBackgroundColor}
        onClosed={() => {
          this.scanner.reactivate();
        }}
      >
        <Text style={styles.text}>{modalText}</Text>
      </Modal>
    );
  }

The problem is my onRead() is an async function but the renderModal() in rendered before i receive the response! Any solution?

Thanks in advance!

As a general thing with Async Functions, the way I go about this in regards to rendering, is to save in your local State an IsLoading: True, and the result of your Functions then changing that to IsLoading: False, and only when that IsLoading is set to False, do rendering, and while it is set to True, display some placeholder that communicates to the user that the data is being processed.

This gives feedback back to the user, and make it responsive.

EDIT:

isLoading(isLoading = true){
this.setState({isLoading})
}

{this.state.isLoading ? <div>placeholder</div> : this.renderModal()}

and inside the return of your async function run isLoading(false) and when you initiate the actual read, run isLoading(true).

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