代码之家  ›  专栏  ›  技术社区  ›  MoKhajavi75

异步呈现本地响应

  •  -1
  • MoKhajavi75  · 技术社区  · 7 年前

    我有一个二维码扫描器,基于服务器的响应,我想用不同的背景色显示一个模式!

    我用过 react-native-qrcode-scanner react-native-modalbox .

    应用程序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>
        );
      }
    

    然后我们有了 OnRead()时 功能是:

    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();
    }
    

    最后是 伦德莫达尔() 以下内容:

    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>
        );
      }
    

    问题是我的 onRead() 是异步函数,但 renderModal() 在我收到回复之前呈现! 有什么解决办法吗?

    事先谢谢!

    1 回复  |  直到 7 年前
        1
  •  2
  •   Vincent Rye    7 年前

    作为异步函数的一个常见问题,我在渲染方面这样做的方式是在本地状态下保存isloading:true,然后将函数的结果更改为isloading:false,并且只有当isloading设置为false时,才进行渲染,并且当它设置为tr时UE,显示一些与正在处理数据的用户通信的占位符。

    这将反馈给用户,并使其响应。

    编辑:

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

    在异步函数的返回中运行 正在加载(错误) 当你开始真正的读取时,运行 正在加载(正确)。