我正在使用Flux的altjs实现从外部api获取数据。api调用从操作中运行良好,返回到存储区,然后在我的组件中触发onChange()函数。我尝试从商店的当前状态设置状态:
import React, { Component, PropTypes } from 'react';
import AppStore from '../../stores/AppStore';
import AppActions from '../../actions/AppActions';
const title = 'Contact Us';
class ContactPage extends Component {
constructor(props) {
super(props);
this.state = AppStore.getState();
}
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
componentWillMount() {
AppActions.getData();
this.context.onSetTitle(title);
AppStore.listen(this.onChange)
}
componentWillUnmount() {
AppStore.unlisten(this.onChange)
}
onChange() {
this.state = AppStore.getState();
}
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{title}</h1>
<span>{this.state.data.id}</span>
</div>
</div>
);
}
}
export default ContactPage;我得到的错误是“无法设置未定义的属性‘状态’”
我的店是这样的:
import alt from '../alt';
import AppActions from '../actions/AppActions';
class AppStore {
constructor() {
this.bindActions(AppActions);
this.loading = false;
this.data = {};
this.error = null
}
onGetDataSuccess(data) {
this.data = data;
}
}
export default alt.createStore(AppStore, 'AppStore');this.state = AppStore.getState()不会在构造函数中抛出任何错误。它只是在onChange()函数中抛出。我应该用什么方式来设置这个州呢?
发布于 2016-02-11 14:21:58
当您使用ES6类时,您需要显式地绑定所有回调,因为没有自动绑定。这可能会让人感到困惑,因为当您使用React.createClass时,可以将所有回调传递到组件中,这就是为什么您可以将this.onChange作为回调传递给组件。
例如:
componentWillMount() {
...
AppStore.listen(this.onChange.bind(this));
}https://stackoverflow.com/questions/35341537
复制相似问题