![](/img/trans.png)
[英]Value was evaluated just now with console.log on JavaScript object
[英]Value below was evaluated just now in console.log after trying to log this.state updated values
我正在嘗試使用新值 xRotation、yRotation 和 zRotation 記錄我更新的 this.state。 但是,當我嘗試記錄 this.state.x、this.state.y、this.state.zi 時,請立即查看此圖標並顯示以下消息。 我認為將異步等待應用於 connect() function 和 navigator.bluetooth.requestDevice({}) 可以解決我的問題,但它沒有。
connect = async () => {
let x = {};
let y = {};
let z = {};
let currentStateX = this.state.x;
let currentStateY = this.state.y;
let currentStateZ = this.state.z;
await navigator.bluetooth.requestDevice({
// filters: [myFilters] // you can't use filters and acceptAllDevices together
optionalServices: [myService],
acceptAllDevices: true
})
.then((device) => {
// save the device returned so you can disconnect later:
myDevice = device;
// connect to the device once you find it:
if(!device.gatt.connect()) {
console.log('no connection')
} else {
return device.gatt.connect();
}
})
.then((server) => {
// get the primary service:
return server.getPrimaryService(myService);
})
.then((service) => {
// get the characteristic:
return service.getCharacteristics();
})
.then((characteristics) => {
// subscribe to the characteristic:
for (let c in characteristics) {
characteristics[c].startNotifications()
.then ((characteristic) => {
characteristic.oncharacteristicvaluechanged = (event) => {
// get the data buffer from the meter:
var xRotation = event.target.value.getFloat32(0,true);
var yRotation = event.target.value.getFloat32(4,true);
var zRotation = event.target.value.getFloat32(8,true);
x[currentStateX] = xRotation;
y[currentStateY] = yRotation;
z[currentStateZ] = zRotation;
}
});
}
})
this.setState({ x: x, y: y, z: z});
console.log(this.state.x);
console.log(this.state.y);
console.log(this.state.z);
}
雖然它對於代碼的 rest 運行良好,因為您已經等待它。 您錯過了一個 function 也是異步的,即this.setState
如果您想在它之后檢查值,您很可能會得到陳舊的值,因為這些值可能尚未設置。
如果要檢查值。 this.setState
有一個可以使用的回調。
例如
this.setState({ x: x, y: y, z: z}, () => {
console.log(this.state.x);
console.log(this.state.y);
console.log(this.state.z);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.