在 React-Native 中访问 this.state [英] Accessing this.state in React-Native
本文介绍了在 React-Native 中访问 this.state的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 React 的新手,请耐心等待.我想将地理位置存储为一个状态.看起来不错,因为位置的任何变化都会触发渲染,这正是我想要的.在开发过程中,我有一个按钮,可以通过访问 lastPosition
手动触发事件.但是当我这样做的时候.状态是未定义的".知道为什么吗?
Hi I'm new to React so bear with me. I'm want to store geoposition as a state. Seems nifty since any change in position will trigger a render, which is exactly what I want. During development I have a button that manual triggers the event by accessing the lastPosition
. But when I do. The state is "undefined". Any clue why?
export default class FetchProject extends Component {
constructor(props) {
super(props);
this.state = {
initialPosition: 'unknown',
lastPosition: 'unknown',
};
}
//code that sets lastposition
componentDidMount() {
....
}
_onPressGET (){
console.log("PressGET -> " + this.state); //undefined
var northing=this.state.initialPosition.coords.latitude;
//triggers error
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress = {this._onPressGET} style = {styles.button}>
<Text>Fetch mailbox</Text>
</TouchableHighlight>
</View>
);
}
}
推荐答案
在 RN 中使用 ES6 类时,注意绑定 this
- this
可能不是你想的那样除非你绑定它.
When using ES6 classes in RN, watch for binding this
- this
may not be what you think unless you bind it.
onPress = { this._onPressGet.bind(this) }
或在构造函数中
constructor(props) {
super(props);
this.state = {
initialPosition: 'unknown',
lastPosition: 'unknown'
};
this._onPressGet = this._onPressGet.bind(this);
}
或者也许是最优雅的方式
or maybe the most elegant way
_onPressGet = () => {
// Function body
}
按照从低到高的顺序.
这篇关于在 React-Native 中访问 this.state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文