在React-Native中访问this.state

TOM*_*MOM 5 javascript setstate reactjs react-native

嗨,我是React的新手,所以请耐心等待.我想将地理位置存储为州.看起来很漂亮,因为任何位置变化都会触发渲染,这正是我想要的.在开发过程中,我有一个按钮,通过访问手动触发事件lastPosition.但是,当我这样做.国家是"未定义的".有什么线索的原因?

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>
       );
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*oad 21

在RN中使用ES6类时,请注意绑定this- this除非您绑定它,否则可能不是您的想法.

onPress = { this._onPressGet.bind(this) }
Run Code Online (Sandbox Code Playgroud)

或者在构造函数中

constructor(props) {
  super(props);

  this.state = {
    initialPosition: 'unknown',
    lastPosition: 'unknown'
  };

  this._onPressGet = this._onPressGet.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

或者也许是最优雅的方式

_onPressGet = () => {
  // Function body
}
Run Code Online (Sandbox Code Playgroud)

从最少到最优惠的顺序.