我正在使用 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() 函数中抛出。我应该在这里设置状态的正确方法是什么?