在学习阮一峰老师的Flux 架构入门教程时,遇到了
this.setState is not a function
我的代码如下
import React, {Component} from 'react';
import ListStore from '../stores/ListStore';
import ButtonActions from '../actions/ButtonActions';
import MyButton from './MyButton';
class MyButtonController extends Component{
constructor(props){
super(props)
this.state = {
items: ListStore.getAll()
}
}
componentDidMount(){
ListStore.addChangeListener(this._onchange);
}
componentWillUnmount(){
ListStore.removeChangeListener(this._onchange);
}
_onchange(){
this.setState({
items: ListStore.getAll()
})
}
createNewItem(event){
ButtonActions.addNewItem('new item');
}
render(){
return(
<MyButton items={this.state.items} onClick={this.createNewItem} />
)
}
}
export default MyButtonController;
当触发_onchange方法时,会提示上述错误
解决方式:
The callback is made in a different context. You need to bind to this in order to have access inside the callback:
即在回调_onchange时,需要修正如下
componentDidMount(){
ListStore.addChangeListener(this._onchange.bind(this));
}
componentWillUnmount(){
ListStore.removeChangeListener(this._onchange.bind(this));
}
解决方案源于
http://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function 点击打开链接