我有一个React
在中可以正常工作的模块ES5
。我正在将其转换为ES6
并6to5
用于转换。一切都可以正常进行,但是在尝试设置时出现运行时错误props
。当我放下debugger
并查看时this
,我看到的this
是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
职务上。当它transpiled
关闭时,它看起来像这样:
_onChange: {
value: function _onChange() {
this.setProps(getAppointments());
},
writable: true,
configurable: true
}
同样,在该函数内部this
是my EventEmitter
。解决此问题的方法是什么?
this.setProps
已弃用,请为此使用状态。它将在0.13中给出警告:
警告:setProps(...)在纯JavaScript React类中已弃用。
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'
}
只要在代码中用“状态”替换所有“属性”的出现,一切都会很好。另外,您可能想要商店的初始状态。
this.state = {
view: 'weeks',
things: CalendarStore.getAppts()
}
另外,createClass不会很快消失,因此随时可以继续使用它。它通常更简单。通常,商店应由mixins处理,这与createClass无关紧要,但在es6类中很难做到。我有一个小库,用于带有react和es6类的mixins。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句