我正在构建一个应用程序,它可以在我每次移动手机时获得手机的速度。我得到了这个值的更新,但我也可以看到下一个警告:
“警告:无法在未安装的组件上执行 React 状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 componentWillUnmount 方法中的所有订阅和异步任务。”
为什么会这样?
我正在使用的代码是:
import React from 'react';
import {
Text
} from 'react-native';
import {
accelerometer,
gyroscope,
setUpdateIntervalForType,
SensorTypes
} from "react-native-sensors";
import { map, filter } from "rxjs/operators";
export class SpeedPanel extends React.Component{
constructor(props) {
super(props);
this.state = {
speed: 0,
subscription: accelerometer
}
}
getData = () => {
const self = this;
const subscription = this.state.subscription
.pipe(map(({ x, y, z }) => x + y + z), filter(speed => speed > 10))
.subscribe(
speed => {
self.setState({speed: speed})
console.log(`You moved your phone with ${speed}`)
},
error => {
console.log("The sensor is not available");
}
);
setTimeout(() => {
// If it's the last subscription to accelerometer it will stop polling in the native API
subscription.unsubscribe();
}, 1000);
}
componentDidMount() {
setUpdateIntervalForType(SensorTypes.accelerometer, 400); // defaults to 100ms
setInterval(this.getData, 400);
}
render () {
return(
<Text>
{'Hello \n'}
{this.state.speed}
</Text>
)
}
}