简体   繁体   English

反应本地错误,因为this.setState不是一个函数

[英]react native getting a error as this.setState is not a function

hi there i"m new to react native during my built process i am getting this error 嗨,我是新来的,我在构建过程中会做出反应,出现此错误

this.setState is not a function

and my code 和我的代码

type Props = {};
export default class App extends Component<Props> {

componentDidMount(){
 Proximity.addListener(this._proximityListener);
}
 _proximityListener(data) {
   this.setState({
     proximity: data.proximity,
     distance: data.distance // Android-only 
   });
 }


  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
            00
        </Text>
      </View>
    );
  }
}

how to solve this error ? 如何解决这个错误? ., 。,

Turn your _proximityListener function into an arrow function like this: 将您的_proximityListener函数变成一个箭头函数,如下所示:

_proximityListener = (data) => {...

This will bind the method to the class and give that method access to the 'this' keyword. 这会将方法绑定到该类,并赋予该方法访问'this'关键字的权限。 :) :)

Change your componentDidMount function to 将您的componentDidMount函数更改为

componentDidMount(){
  Proximity.addListener(this._proximityListener.bind(this));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM