简体   繁体   English

在React-Native中访问this.state

[英]Accessing this.state in React-Native

Hi I'm new to React so bear with me. 嗨,我是React的新手,所以请耐心等待。 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 . 在开发过程中,我有一个按钮,通过访问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>
       );
    }
}

When using ES6 classes in RN, watch for binding this - this may not be what you think unless you bind it. 当RN使用ES6类,注意结合this - this可能不是你的想法,除非你绑定。

onPress = { this._onPressGet.bind(this) }

or in the constructor 或者在构造函数中

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
}

In order from least to most preferential. 从最少到最优惠的顺序。

Quoted from React Docs : 引自React Docs

You have to be careful about the meaning of this in JSX callbacks. 在JSX回调中你必须要小心这个含义。 In JavaScript, class methods are not bound by default. 在JavaScript中,默认情况下不会绑定类方法。 If you forget to bind this.handleClick and pass it to onClick , this will be undefined when the function is actually called. 如果您忘记绑定 this.handleClick并将其传递给onClick ,则在实际调用该函数时,这将是undefined的。

This is not React-specific behavior; 这不是特定于React的行为; it is a part of how functions work in JavaScript. 它是JavaScript中函数如何工作的一部分。 Generally, if you refer to a method without () after it, such as onClick={this.handleClick} , you should bind that method. 通常,如果您在其后引用没有()的方法,例如onClick={this.handleClick} ,则应该绑定该方法。

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

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