2017-04-26 66 views
4

我知道讨论范围问题的类似线程。反应 - 无法读取null属性'setState'

使用下列组件

import React from 'react'; 
import ReactDOM from 'react-dom'; 

class Example extends React.Component { 

    constructor(props) { 
     super(props); 

     this.state = { 
      counter: 0 
     } 
    } 

    addMore() { 
     this.setState({ 
      counter: this.state.counter + 1 
     }); 
    } 

    render() { 
     return (

      <div onClick={ this.addMore }> 
       <p>counter: { this.state.counter }</p> 
      </div> 

     ); 
    } 
} 

if (document.getElementById('example')) { 
    ReactDOM.render(<Example />, document.getElementById('example')); 
} 

当你点击divCannot read property 'setState' of null

我知道你可以做这样的事情this.addMore.bind(this)但是这一切似乎不可思议额外的样板式的代码只是为了让工作。


什么被认为是最优雅的方式来做到这一点?当然,人们必须有一个有利的方式,而不是眼睛疼痛?

+0

类的属性提案可能是最优雅的解决方案,如下所示:http://stackoverflow.com/a/34050078/218196。 –

+0

http://blog.andrewray.me/react-es6-autobinding-and-createclass/ –

回答

7

您需要将正确的this上下文绑定到该函数,并且可以通过将this.addMore = this.addMore.bind(this);添加到构造函数中来完成此操作。

constructor(props) { 
    super(props); 

    this.state = { 
     counter: 0 
    } 

    this.addMore = this.addMore.bind(this); 
} 

在ES5 React.createClass所有功能都自动绑定到正确的this但ES6类正确this上下文不会自动绑定。 reference

这被称为绑定在构造函数中,这是目前在React文档中为“在应用程序中获得更好性能”推荐的方法。 reference

10
addMore =() => { 
    this.setState({ 
    counter: this.state.counter + 1 
    }); 
} 

箭头语法需要照顾的this

检查这个伟大的链接了解更多信息绑定的,它显示了许多方法来完成这个 http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html

+1

尽管这不是有效的ES6。 –