Reactjs,这.上下文在构造函数方法中未定义
Reactjs, this.context is undfined in constructor method
我实际上正在尝试开发一个简单的组件,对应于一个列表,当我按下一个按钮时,我将再填充一个项目。
我的问题是我使用ES6,所以我不使用getInitialState,我使用构造函数进行初始化,就像在文档中解释的那样。
我的问题是,现在,这。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;
我只是想在构造函数中预加载数组,即使它是空的或不空的,这正是我的store返回的:
从' flexible/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;
谢谢你的帮助
你面临的问题是因为你的组件应该是无状态的,我再怎么说也不为过,state应该存在于你的商店里,(I-state,"可以")。生活在你的组件中,但这是有争议的)
你应该做的是使用一个更高级的组件,把你的react组件封装在一个更高级的组件中,让那个组件从store中获取状态,并把它作为props传递给你的组件。
这样你就不需要初始化状态,你只需要设置你的defaultProps和propTypes。
这样你的组件是无状态的,你可以完全利用react的生命周期,它也变得可重用,因为你不需要在你的组件中获取实际数据的逻辑。
好读
-
props vs state: https://github.com/uberVU/react-guide/blob/master/props-vs-state.md)
-
高级组件:http://browniefed.com/blog/2015/05/02/react/
希望这对你有帮助
相关文章:
- 骨干's Router.execute(callback,args,name)方法获取未定义的名称
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 使用javascript ajax post方法的未定义偏移PHP错误
- jQuery验证器添加方法未定义
- 定义的静态方法未定义
- jQuery Validate() 和 Valid() 方法未定义或不起作用
- 为什么内部函数中当前对象的方法未定义
- 如何解决“不能调用方法...未定义“错误
- 得到"无法调用方法..未定义的“;JavaScript和Mustache出现错误
- JavaScript方法未定义
- initialize()方法未定义
- ExpressJS PUT方法未定义的对象问题
- JavaScript - Prototype方法未定义
- 映射内匿名函数内的方法未定义
- 在事件处理程序中调用方法未定义
- 在setTimeOut函数中传递多个参数会抛出Uncaught ReferenceError:方法未定义(匿名函数)
- Javascript对象方法未定义
- app()方法未定义
- 未捕获的类型错误:不能调用方法'未定义使用Ckeditor
- QuickTime对象的SetURL方法未定义