reactjs – 如何在将React模块转换为ES6类时解决`this`

前端之家收集整理的这篇文章主要介绍了reactjs – 如何在将React模块转换为ES6类时解决`this`前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个在ES5中工作正常的React模块.我正在将其转换为ES6并使用6to5进行转换.一切都很好,但是当我试图设置我的道具时,我遇到了运行时错误.当我删除调试器并查看它时,我发现这是EventEmitter而不是类.这是我的代码
var React = require('react');

import CalendarStore from './../stores/calendar.store.js';

function getAppointments() {
  return {appts: CalendarStore.getAppts()}
}

export default class extends React.Component{
  constructor(props) {
    super(props);
    this.props = {
      view: 'weeks'
    }
  }

  changeView(child,view) {
    this.setProps({view: view});
  }

  componentWillMount() {
     CalendarStore.addChangeListener(this._onChange);
  }

  _onChange() {
    this.setProps(getAppointments());
  }

  ....
};

我遇到问题的地方是我的changeView功能.当它被编译时,它看起来像这样:

_onChange: {
      value: function _onChange() {
        this.setProps(getAppointments());
      },writable: true,configurable: true
    }

同样,在该函数内部,这是我的EventEmitter.解决这个问题的方法是什么?

不推荐使用this.setProps,为此使用状态.它会在0.13中给你这个警告:

Warning: setProps(…) is deprecated in plain JavaScript React classes.

此外,es6类方法不会自动响应,因此您需要手动绑定它.您可以使用.bind(this),也可以使用箭头功能.但是,对于外部发射器,您需要保留参考.

你可以摆脱_onChange:

this._calendarListener = e => this.setState({things: e});
CalendarStore.addChangeListener(this._calendarListener);

或者在构造函数中绑定:

constructor(props){
   ...
   this._onClick = this._onClick.bind(this);
}

不要忘记在componentWillUnmount中取消绑定事件:

componentWillUnmount(){
    CalendarStore.removeChangeListener(this._onClick);
    // or 
    CalendarStore.removeChangeListener(this._calendarListener);
}

添加事件侦听器应该在componentDidMount中完成,而不是componentWillMount.构造函数替换es6类中的componentWillMount.

这段代码非常糟糕……你要重写道具反应集:

this.props = {
  view: 'weeks'
}

只需在代码中用’state’替换所有出现的’props’,一切都会好的.你也可能想要商店的初始状态.

this.state = {
  view: 'weeks',things: CalendarStore.getAppts()
}

此外,createClass不会很快消失,所以请随时继续使用它.它通常更简单.商店通常应该由mixin处理,这对于createClass来说是微不足道的,但在es6类中更难做到.我有一个mixins with react and es6 classes的小型图书馆.

原文链接:https://www.f2er.com/react/300936.html

猜你在找的React相关文章