我做错了什么,我一直得到TypeError:无法读取null的属性'count'。我没有正确设置初始状态吗?
import React from 'react';
class User extends React.Component {
super(props){
this.state = {
count: 0
}
}
increment(){
this.setState({ count: this.state.count + 1 })
}
render(){
return(<div>
<button
onClick={this.increment}>
{this.state.count}
</button>
</div>)
}
}
export default User;
答案 0 :(得分:1)
将this
设置为.increment
方法,因为当您将方法.increment
传递给onClick
时,会丢失与User
组件相关的上下文。而不是super(props)
,您必须使用constructor(props)
;
class User extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
this.increment = this.increment.bind(this);
}
increment(){
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<div>
<button
onClick={this.increment}
>
{ this.state.count }
</button>
</div>
)
}
}
ReactDOM.render(<User />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
你也可以使用箭头功能,如此
onClick={() => this.increment() }