我实际上是在尝试开发一个与列表相对应的简单组件,当我按下按钮时,我又填充了一个项目。
我的问题是我使用 ES6,所以我不使用 getInitialState,我使用构造函数进行初始化,就像文档中解释的那样。
我的问题是,现在 this.context 在我的构造函数中未定义,我无法直接在构造函数中获取我的第一次数组(或预加载的数组):
import React from 'react';
import ListStore from '../stores/ListStore';
class Client extends React.Component {
constructor(props){
super(props);
this.state = this.getStoreState(); // throw me that in getStoreState, this.context is undefined
}
static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired
};
componentDidMount() {
this.context.getStore(ListStore).addChangeListener(this._onStoreChange.bind(this));
}
componentWillUnmount() {
this.context.getStore(ListStore).removeChangeListener(this._onStoreChange.bind(this));
}
_onStoreChange () {
this.setState(this.getStoreState());
}
getStoreState() {
return {
myListView: this.context.getStore(ListStore).getItems() // gives undefined
}
}
add(e){
this.context.executeAction(function (actionContext, payload, done) {
actionContext.dispatch('ADD_ITEM', {name:'toto', time:new Date().getTime()});
});
}
render() {
return (
<div>
<h2>Client</h2>
<p>List of all the clients</p>
<button onClick={this.add.bind(this)}>Click Me</button>
<ul>
{this.state.myListView.map(function(test) {
return <li key={test.time}>{test.name}</li>;
})}
</ul>
</div>
);
}
}
export default Client;
我只想在构造函数中预加载数组,即使它是否为空,这正是我的商店返回的内容:
从 'fluxible/addons/BaseStore' 导入 BaseStore;
class ListStore extends BaseStore {
constructor(dispatcher) {
super(dispatcher);
this.listOfClient = [];
}
dehydrate() {
return {
listOfClient: this.listOfClient
};
}
rehydrate(state) {
this.listOfClient = state.listOfClient;
}
addItem(item){
this.listOfClient.push(item);
this.emitChange();
}
getItems(){
return this.listOfClient;
}
}
ListStore.storeName = 'ListStore';
ListStore.handlers = {
'ADD_ITEM': 'addItem'
};
export default ListStore;
谢谢你的帮助