我知道有类似的线程讨论范围问题。
使用以下组件
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'));
}
当您单击div
时你得到Cannot read property 'setState' of null
我知道你可以做类似 this.addMore.bind(this)
的事情但所有这些看起来都很奇怪,额外的样板样式代码只是为了让它工作。
什么被认为是最优雅的方法?人们肯定有一种偏好的方式,除了让人眼睛酸痛之外,还有其好处?
最佳答案
addMore = () => {
this.setState({
counter: this.state.counter + 1
});
}
箭头语法会为您处理 this
绑定(bind)
查看这个很棒的链接以获取更多信息,它显示了实现此目的的多种方法 http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html
关于reactjs - React - 无法读取 null 的属性 'setState',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43644583/