2016-06-01 57 views
0

我得到一个错误that.setState不是一个函数,一个独立的函数内部

that.setState是不是一个函数

我看到了问题 React this.setState is not a function

仍我无法让它工作。

但我的是一个独立的功能。此外,我保存的背景和使用它像:

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)); 

但给出UnexpectedToken Error!

我将它传递这样

<Buttons onUpdate={this.onUpdate} /> 

,然后从那里调用函数,但我使用“那个”了的setState。

这是我的第一个应用程序,很抱歉,如果有非常明显的错误!

+0

你为什么要存储背景?你不能只用'this'而不是'that'?使用'that'模式大部分被es6所弃用。 –

+2

而且你不需要绑定那样的箭头功能! 您能否为我们发布完整的组件? – Syberic

+0

@Syberic,我的第一个应用程序,尝试不同的东西,以某种方式得到它的工作:p基于在我指出的stackoverflow中的问题,我知道这是错误的,它提供了一个错误,正如我所提到的。我仍然需要学习正确的方法。 –

回答

0

当你写这样

<Buttons onUpdate={this.onUpdate} /> 

的功能的onUpdate势必与窗口,这就是为什么没有定义的setState。

你可以做这样的

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

或声明的onUpdate像

updateResult = item => {...} 

这个箭头功能将与此(类)的约束