this.setState is not a function

在学习阮一峰老师的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 点击打开链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值