[英]Uncaught TypeError: Cannot read property 'setState' of null React
I have the following react page and am getting我有以下反应页面并且正在获取
Uncaught TypeError: Cannot read property 'setState' of null
when using the counter.使用计数器时。 It seems to have to do with the
this
used by setState似乎与 setState 使用的
this
<!DOCTYPE html>
<html>
<head>
<title>counter</title>
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.0.0-beta.3/react-router.min.js"></script>
<head>
<body>
<div id="entry"></div>
<script type="text/babel">
var destination = document.querySelector("#entry");
class Counter extends React.Component {
constructor() {
super();
this.state = { value: 0};
}
increment(){
this.setState(function(prevState){
value: prevState.value + 1
});
};
decrement(){
this.setState(prevState => ({
value: prevState.value - 1
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
ReactDOM.render(
<div>
<Counter/>
</div>,
destination
)
</script>
</body>
</html>
I just changed increment
to an old style function and that didn't work.我只是将
increment
更改为旧式函数,但没有用。
You'd have to pass the context around to your custom functions in ES6 mode of writing.您必须以 ES6 的编写模式将上下文传递给您的自定义函数。
There are many ways to do it, a good starting point is this sitepoint article here.有很多方法可以做到这一点,一个很好的起点是这里的站点点 文章。
As a start,change your constructor as -首先,将您的构造函数更改为 -
constructor() {
super();
this.state = { value: 0};
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
You can do the same in onClick
as well, but IMHO this seems neater你也可以在
onClick
做同样的事情,但恕我直言,这看起来更整洁
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.