我实际上是在尝试开发一个与列表相对应的简单组件,当我按下按钮时,我会再填写一个项目.
我的问题是我使用ES6,所以不使用getInitialState,而是使用构造函数进行初始化,如文档中所述.
我的问题是,现在,在构造函数中未定义this.context,并且无法直接在consntructor内部获取我的第一个时间数组(或预加载的数组):
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 (
Client
List of all the clients
Click Me
{this.state.myListView.map(function(test) {
return
{test.name};})}
);
}
}
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;
谢谢你的帮助
解决方法:
您面临的问题是因为您的组件应该是无状态的,
我不能这么说,状态应该存在于您的商店中(UI状态,“可以”存在于您的组件中,但这值得商))
您应该做的是使用一个更高级别的组件,将您的react组件包装在一个更高级别的组件中,让该组件从商店中获取状态,并将其作为道具传递给您的组件.
这样,您不需要初始状态,只需设置defaultProps和propTypes.
这样,您的组件是无状态的,并且您可以充分利用react生命周期,并且还可以重用,因为您没有在组件中获取实际数据的逻辑.
好读
希望这可以帮助 :)
标签:reactjs,flux,fluxible,javascript
来源: https://codeday.me/bug/20191027/1948336.html