React Native:如何使用react-native-sensors在传感器订阅中添加代码

问题描述 投票:0回答:1

我正在使用react-native-sensors来获取加速度计读数。它正确读取传感器值。作为React Native的新手,我无法弄清楚如何添加代码来计算sensor.subscribe方法中的加速度向量。

import { 
setUpdateIntervalForType, 
SensorTypes, 
accelerometer, 
gyroscope 
} from 'react-native-sensors';

........

export default class Accelerometer extends Component {

constructor(props) {
    super(props);

    setUpdateIntervalForType(SensorTypes.accelerometer, 200);
    this.accelSubscription = accelerometer.subscribe(({ x, y, z, timestamp }) =>
        this.setState({
            accel_x: x,
            accel_y: y,
            accel_z: z,
        })
    );

    this.state = {
        acceleration: 0,
        accel_x: 0,
        accel_y: 0,
        accel_z: 0,
    };
}

这是我想要在每次获得新的加速度计读数时执行的计算代码:

    const accelx = this.state.accel_x;
    const accely = this.state.accel_y;
    const accelz = this.state.accel_z;
    const lastAccel = this.state.acceleration;
    const currAcceleration = Math.sqrt((accelx * accelx) + (accely * accely) + (accelz * accelz));
    //I need to delta value to detect changes
    const accelerationDelta = currAcceleration - lastAccel;
    this.setState({
        acceleration: currAcceleration,
    });

如果我将代码直接放在accelerometer.subscribe()中,它将抛出错误。我怎么能做到这一点?

react-native accelerometer sensors react-native-sensors
1个回答
0
投票

你应该把你的代码放在括号内。 在箭头功能中如果你不使用{}那么你只能写一行

accelerometer.subscribe(({ x, y, z, timestamp }) =>{
    this.setState({ accel_x: x });
    alert('Test this');
}
© www.soinside.com 2019 - 2024. All rights reserved.