Javascript React本机函数返回未定义的
我正在尝试在react native中创建蓝牙应用程序。为了迎接挑战,我决定创建自己的本机蓝牙模块。现在,如果蓝牙连接已启用或已连接到任何设备,我希望呈现有关蓝牙连接的一些状态数据 我有一个调用函数Bluetooth.isEnabled的函数。Bluetooth.isEnabled有一个回调参数,该参数将获取Bluetooth的状态true(如果已启用)或false(否则)Javascript React本机函数返回未定义的,javascript,android,reactjs,bluetooth,native,Javascript,Android,Reactjs,Bluetooth,Native,我正在尝试在react native中创建蓝牙应用程序。为了迎接挑战,我决定创建自己的本机蓝牙模块。现在,如果蓝牙连接已启用或已连接到任何设备,我希望呈现有关蓝牙连接的一些状态数据 我有一个调用函数Bluetooth.isEnabled的函数。Bluetooth.isEnabled有一个回调参数,该参数将获取Bluetooth的状态true(如果已启用)或false(否则) bluetooth_isEnabled(){ Bluetooth.isEnabled((status)=
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将始终返回未定义。我在Bluetooth.isEnabled功能中检查了consoled.log状态,结果是真的
为什么bluetooth isEnabled返回未定义?您的bluetooth isEnabled函数是一个异步函数。您应该使用Promissions或async/await结构来返回值。使用async/await更新函数以返回承诺
bluetooth_isEnabled = async()=>{
const status = await Bluetooth.isEnabled();
})
然后将其用作:
this.bluetooth_isEnabled.then((status) => {
this.setState({status:status})
})
您不应该使用这个.variable\u名称访问变量,而应该使用state
bluetoothStatus(){
var status = this.state.status;
console.log(status)
if(status()){
return(
<Text>ENABLED</Text>
)
}
else{
return(
<Text>DISABLED</Text>
)
}
}