Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native 为什么会';这是数据';超出范围?_React Native - Fatal编程技术网

React native 为什么会';这是数据';超出范围?

React native 为什么会';这是数据';超出范围?,react-native,React Native,我有一个按钮,它在ApproximatePress上调用一个过程,但该过程没有看到“this.data” <Button title="<20" onPress={onApproximateAgePress}/> onApproximateAgePress () { console.log('onApproximateAgePress') ; // outputs onApproximateAgePress console.log(this.data

我有一个按钮,它在ApproximatePress上调用一个过程,但该过程没有看到“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,

        ...

  }),
}

onApproximateAgePress(){
console.log('onApproximateAgePress');//输出onApproximateAgePress
console.log(this.data);//输出null
}
//“Immutable.js”状态数据的Getter。。。
获取数据(){
返回此.state.data;
}
//“Immutable.js”状态数据的Setter。。。
设置数据(数据){
this.setState({data});
}
状态={
数据:fromJS({
肖克:错,
...
}),
}
我还有其他组件,它们也以类似的方式连接起来,但它们确实看到了这一点

如果我把电话改成

 <Button title="<20" onPress={(e)=>console.log(this.data) }/>
console.log(this.data)}/>
我得到一个包含有效值的日志


为什么“this.data”会超出范围?

在这两种备选方案中,有一个主要区别,第一种方法是为onPress事件分配回调,第二种方法是使用arrow函数。 那么箭头函数做什么呢?对于starter,它将“this”的词法范围绑定到您正在记录的块
this.data

阅读更多信息:

因此,您在onApproximateAgePress()中引用的
不等于此组件的当前实例,您应该绑定它

或 解决方案一:

解决方案二:
onApproximateAgePress()}/>


您应该能够访问此数据,从而访问此.data

什么是
此.data
?它是react本机组件中的静态属性吗?它是一个“Immutable.js”状态数据对象。在问题中添加了示例代码。javascript中的概念有点不同。直接将该方法传递给ApproximateAgePress可能会更改此方法的上下文。我鼓励大家看看这个:解决方案II由于某种原因失败了。解决方案1奏效了。谢谢