javascript - React/ES6 类中的范围

标签 javascript reactjs ecmascript-6

<分区>

我在理解 ES6 类中 this 的范围时遇到了一些问题。在这里,我有组件:

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      credentials: {
        v: '3.exp',
        key: null,
      },
      coordinates: {
        lat: 51.5258541,
        lng: -0.08040660000006028,
      },
    };

    Meteor.call('googleMapsApiKey', (err, res) => {
      if (!err) {
        this.setState({ key: res });
      }
    });
  }

  onMapCreated(map) {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(() => {
        this.setState({
          coordinates: {
            lat: this.lat,
            lng: this.lng,
          },
        });
      });
    } else {
      console.log('geolocation not supported');
    }

    map.setOptions({
      disableDefaultUI: true,
    });
  }

...

我在 onMapCreated(map) 函数中的第 33 行遇到错误,特别是对 this.setState 的调用。

enter image description here

我怀疑我缺少某种绑定(bind),或者 this 的范围指的是 navigator.geolocation,因此不再引用该类。大家怎么看?

最佳答案

不是ES6的问题,是绑定(bind)问题还是React。你应该在 React 的构造函数中绑定(bind)你的方法:

this.onMapCreated = this.onMapCreated.bind(this);

这样 this 就可以在你的方法中被识别。

嗯,可能是ES6的问题,看这个docs react :

With React, every method is automatically bound to its component instance (except when using ES6 class syntax).

关于javascript - React/ES6 类中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481210/

相关文章:

javascript - AngularJS:编译指令的输出

reactjs - 如何通过一劳永逸地重新渲染来修复图像闪烁?

javascript - react-easy-state - 一个商店通过去抖触发其他商店的变化

javascript - 无法更新 ReactJS 组件

javascript - 在 Javascript 中解构赋值的好处

javascript - 错误 : incompatible types: MainActivity cannot be converted to FragmentActivity . 添加包(新 ReactDatePackage(本))

javascript - 匹配带引号和不带引号的相同字符串的正则表达式

javascript - 在 typescript 中精炼泛型

javascript - 在第一个元素的处理结束之前,不要处理 forEach 循环中的下一个元素

javascript - 三元运算符多个语句