0

I've got a button that calls a procedure onApproximateAgePress which fails to see 'this.data'.

 <Button title="<20" onPress={onApproximateAgePress}/>  

 onApproximateAgePress () {
    console.log('onApproximateAgePress') ; // outputs onApproximateAgePress 
    console.log(this.data) ; // outputs null
 }

  // Getter for "Immutable.js" state data...
  get data() {
    return this.state.data;
  }

  // Setter for "Immutable.js" state data...
  set data(data) {
    this.setState({ data });
  }

  state = {
      data: fromJS({
        showApproximateAgePicker: false,

        ...

  }),
}

I have other components that have been wired up in a similar way but they do see this.data.

If I change the call to

 <Button title="<20" onPress={(e)=>console.log(this.data) }/>

I get a log of with valid values.

Why would 'this.data' go out of scope?

Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64
  • what is `this.data`? is it a static property in your react-native component? – Mμ. Jun 23 '17 at 05:59
  • It's an "Immutable.js" state data object. Added example code to the question. – Keith John Hutchison Jun 23 '17 at 06:05
  • 1
    The concept of this in javascript is a little different. Passing the method onApproximateAgePress directly may change the context of this. I encourage you to have a look at this: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Mμ. Jun 23 '17 at 06:14

1 Answers1

1

Well in both the alternatives , there is one major difference , on the first approach you are just assigning a callback to the onPress Event , where as in second you are using arrow function. So what does arrow function do? for starter it binds the lexical scope of 'this' ,in second case to the block where you are logging this.data

Read for More : Arrow Functions

so this you are referring in onApproximateAgePress() does not equal to current instance of this component, you should bind it.

or Solution I : <Button title="<20" onPress={this.onApproximateAgePress.bind(this)}/>

Solution II : <Button title="<20" onPress={() => onApproximateAgePress()}/>

You should be able to access this and hence this.data

Arnav Yagnik
  • 782
  • 1
  • 4
  • 14