在下面的代码中,我尝试获取加速度计的值和时间戳,并在文本视图中显示它们。如果我注释掉行setVal(timestamp),那么用console.log({x, y, z, timestamp})显示的值是正确的(正如预期的那样)。但是,如果我取消对setVal(timestamp)的注释,那么随着时间的推移,使用console.log显示的值最终会变得完全相同。
不确定我做错了什么。我猜setVal(timestamp)以某种方式覆盖了变量timestamp的值。有没有更正确、更好的方法来做到这一点?
import React, { useState } from "react";
import {View, Text} from 'react-native';
import {accelerometer} from 'react-native-sensors';
export default function App(props) {
const [val, setVal] = useState(1);
const subscription = accelerometer.subscribe(({x, y, z, timestamp}) => {
console.log({x, y, z, timestamp});
setVal(timestamp);
});
return (
<View>
<Text>Timestamp: {val}</Text>
</View>
);
}发布于 2021-01-08 00:31:33
如果不调用setVal(时间戳),那么它不会重新呈现。但是当你把这行放进去的时候,它就会不断地重现。尝试像这样替换您的代码。因此,订阅是一次完成的,而不是一次又一次。
useEffect(()=> {
const subscription = accelerometer.subscribe(({x, y, z, timestamp}) => {
console.log({x, y, z, timestamp});
setVal(timestamp);
})},[])https://stackoverflow.com/questions/65615440
复制相似问题