我有一个问题,我想触发一个功能或其他一些东西,如果在加速度传感器的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',
},
});
您不应该在函数内使用关键字this
,请利用钩子useRef
以获得类似的行为。
useRef
useEffect(() => {
_toggle();
return () => {
_unsubscribe();
};
}, []);