记一个报错。
更新state值报错,Cannot read properties of undefined (reading 'setState')
import React from "react";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "Hello",
};
// 修改这行下面的代码
// 修改这行上面的代码
}
handleClick() {
this.setState({
text: "You clicked!",
});
}
render() {
return (
<div>
{/* 修改这行下面的代码 */}
<button onClick={this.handleClick}>Click Me</button>
{/* 修改这行上面的代码 */}
<h1>{this.state.text}</h1>
</div>
);
}
}
export default MyComponent;
更新state值报错,
Cannot read properties of undefined (reading 'setState')
似乎需要更改this指向,不太理解。
// 修改这行下面的代码
this.handleClick = this.handleClick.bind(this);
// 修改这行上面的代码
点击后值更新
又发现一个方法,就是修改成箭头函数
handleClick = () => {
this.setState({
text: "You clicked!",
});
};
依然可以实现修改值