【问题标题】:React native function returns undefined [duplicate]反应本机函数返回未定义[重复]
【发布时间】:2020-07-18 18:49:36
【问题描述】:

我正在尝试在本机反应中创建一个蓝牙应用程序。为了提出挑战,我决定创建自己的原生蓝牙模块。现在我想渲染一些关于蓝牙连接的状态数据(如果它已启用或连接到任何设备)。

我有一个调用函数 Bluetooth.isEnabled() 的函数。 Bluetooth.isEnabled 有一个回调参数,它将获取蓝牙的状态(true 已启用,否则为 false)。

 bluetooth_isEnabled(){
   
    Bluetooth.isEnabled((status)=>{
      console.log(status)
      return status;
      

    })
  

这里是构造函数

class App extends Component {
  constructor(props){

    super(props)
    
    this.state = {
    
      isConnected: false,
      isEnabled: false 
    }
    this.checkConnection = this.checkConnection.bind(this);
    this.bluetooth_isEnabled = this.bluetooth_isEnabled.bind(this);
    this.bluetoothStatus = this.bluetoothStatus.bind(this);
  }
.
.
.

在以下函数中,我试图检查蓝牙是否已启用但状态未定义

bluetoothStatus(){
    var status = this.bluetooth_isEnabled()
    console.log(status)
    if(this.bluetooth_isEnabled()){
      return(
        <Text>ENABLED</Text>
      )
    }
    else{
      return(
        <Text>DISABLED</Text>
      )
    }
    
  }

bluetooth_isEnabled() 将始终返回未定义。我检查了 consoled.log Bluetooth.isEnabled() 函数中的状态,它是真的。

为什么 bluetooth_isEnabled() 返回 undefined?

【问题讨论】:

    标签: javascript android reactjs bluetooth native


    【解决方案1】:

    您的 bluetooth_isEnabled 函数是一个异步函数。您应该使用 Promise 或 async/await 结构来返回一个值。使用 async/await 更新您的函数以返回一个承诺

     bluetooth_isEnabled = async()=>{
    
       const status = await Bluetooth.isEnabled();      
    
    })
    

    然后将其用作:

    this.bluetooth_isEnabled.then((status) => {
       this.setState({status:status})
    })
    

    而且您不应该使用 this.variable_name 访问变量,而是使用 state。

    bluetoothStatus(){
     var status = this.state.status;
     console.log(status)
     if(status()){
      return(
        <Text>ENABLED</Text>
      )
    }
    else{
      return(
        <Text>DISABLED</Text>
      )
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-13
      • 2018-02-21
      • 2018-10-30
      • 1970-01-01
      • 2013-06-26
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多