setState不是一个函数,在一个独立函数内部



我收到一个错误

setState不是函数

我看到了问题React this.setState不是函数

但我还是无法让它发挥作用。

但我的职能是独立的。此外,我存储上下文并使用它,如:

componentDidMount(){
that=this;
}

然后

updateResult(item){
result.push(item);
that.setState({result: result});
}

我还在构造函数中绑定它

this.updateResult = this.updateResult.bind(this);       
this.resetResult = this.resetResult.bind(this);

我还试着在一个功能上做

onUpdate(item, ()=>{
itemList.push(item);
that.setState({itemList: itemList});
}.bind(this));

但给出CCD_ 1

我确实像这个一样通过

<Buttons onUpdate={this.onUpdate} /> 

然后从那里调用函数,但我对setState使用"that"。

这是我的第一次申请,如果有非常明显的错误,很抱歉!

当你像这样写时

<Buttons onUpdate={this.onUpdate} /> 

onUpdate函数与window绑定,这就是没有定义setState的原因。

你可以像一样

<Buttons onUpdate={this.onUpdate.bind(this)} /> 

或者像一样声明onUpdate

updateResult = item => {...}

此箭头函数将与此(您的类)绑定

最新更新