下面是一段简略的代码:我想通过外部调用静态方法,设置this.setState
class Box extends React.Component {
...
static update(user) {
this.setState({
onlineuser: user
})
}
...
}
Box.update(user);
console提示:this.update is not a function
怎么正确绑定this呢?
试了Stack里面的几种方法还是不行
http://stackoverflow.com/questions/33381756/this-setstate-is-not-a-function
http://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function
题主千万别让es2015的语法给忽悠了啊。
理论上讲,静态方法中怎么可能存在this对象呢?
这里出现this正是因为它要编译成es5的代码去执行导致的。而es5中,this对象是分成定义时,调用时,和运行时几种情况的。所以this不确定是正常的,也是很容易理解的啊……
这个例子给大家吧:
class Home extends React.Component{
constructor(props){
super(props);
this.state = {
loadingMore:false,
noMore:false,
spinnerLoading:false,
product:[]
}
//分2列
this.groupNum = 2;
this.totalPage = 0;
this.onEndReached = this.onEndReached.bind(this);
this.renderFooter = this.renderFooter.bind(this);
};
.....
}
按照面向对象的思想,题主这样写明显有问题。静态方法属于类,而setState是对象的方法。题主试图在类方法中调用对象方法,这是不符合逻辑思维的。
可以设想一下一种情况,你这个类有多个对象,那么你这里的setState到底是哪个对象的?蒙蔽了吧?所以说这个this是不确定的,除非你调用的时候绑定一下对象的this
首先,我已经也试了几种方法绑定this。 还是报错。
然后认真读了官方给出的使用静态方法时的问题。
https://facebook.github.io/react/docs/component-specs.html
the methods do not have access to the props or state of your components. 这里说react默认不能通过静态方法设置state。