【问题标题】:Trigger a Counter up function with a accelerometer sensor使用加速度计传感器触发计数器功能
【发布时间】:2020-05-29 14:44:59
【问题描述】:

我遇到的问题是,如果加速度计传感器的 x 轴上达到特定数字,我想触发一个函数或其他东西来计数一个数字。 我尝试了一个位于渲染部分的函数,但出现了无法计数的问题。

之后我尝试将它写在一个钩子中,然后我得到了这个错误。

https://i.stack.imgur.com/4avBY.png

这就是我目前所得到的

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Accelerometer } from 'expo-sensors';

export default function App() {
  const [data, setData] = useState({});
  const [count, setCount] = useState(0);

  useEffect(() => {
    _toggle();
  }, []);

  useEffect(() => {
    return () => {
      _unsubscribe();
    };
  }, []);

  const _toggle = () => {
    if (this._subscription) {
      _unsubscribe();
    } else {
      _subscribe();
    }
  };

  const _subscribe = () => {
    this._subscription = Accelerometer.addListener(accelerometerData => {
      setData(accelerometerData);
    });
  };

  const _unsubscribe = () => {
    this._subscription && this._subscription.remove();
    this._subscription = null;
  };

  let { x, y, z } = data;
  return (
    <View style={styles.sensor}>
      <Text style={styles.text}>Accelerometer: (in Gs where 1 G = 9.81 m s^-2)</Text>
      <Text style={styles.text}>
        x: {x} y: {y} z: {z}
      </Text>
      <View style={styles.buttonContainer}>
        {x > 0.7 ? setCount(count + 1) : <Text>doesnt work</Text>}
        <Text>{count}</Text>
      </View>
    </View>
  );
}



const styles = StyleSheet.create({
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'stretch',
    marginTop: 15,
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#eee',
    padding: 10,
  },
  middleButton: {
    borderLeftWidth: 1,
    borderRightWidth: 1,
    borderColor: '#ccc',
  },
  sensor: {
    marginTop: 45,
    paddingHorizontal: 10,
  },
  text: {
    textAlign: 'center',
  },
});

【问题讨论】:

    标签: javascript reactjs react-native accelerometer sensors


    【解决方案1】:

    您不应该在函数中使用关键字this,请使用钩子useRef 来获得类似的行为。

    useEffect(() => {
        _toggle();
    
         return () => {
          _unsubscribe();
        };
    
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      相关资源
      最近更新 更多