如何解决反应本机传感器数据检索未安装的组件警告
我正在构建一个应用程序,每次移动时都能获得手机的速度。我得到了这个值的更新,但我也可以看到下一个警告:
"警告:无法对卸载的组件执行 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>
)
}
}
解决方法
不用担心...我重新加载了这个应用程序,但没有出现更多警告。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。