🤔 문제발생
필자가 react에서 setState를 사용하다가 TypeError: Cannot read properties of undefined(reading 'setState') 오류가 브라우저 콘솔창에 나타났다. 이를 해결하기 위해 bind 방법과 화살표 함수를 써야한다.
🎉 해결방법 1
class Lostpassword extends Component {
constructor(props) {
super(props);
this.state = {number :''};
this.plus = this.plus.bind(this);
}
plus(){
const a = 1;
const b = a + a;
{this.setState({number:b})}
}
- 첫 번째, this.setState가 있는 함수를 bind 해주어야 한다.
- 두 번째, state를 정의하는 곳에 this.plus = this.plus.bind(this); 게 바인딩 시켜주면 된다.
🎉 해결방법 2
class Lostpassword extends Component {
constructor(props) {
super(props);
this.state = {number :''};
}
plus = () => {
const a = 1;
const b = a + a;
{this.setState({number:b})}
}
- 첫 번째, 함수를 화살표 함수로 만든다.
👏 결과
결과적으로 오류는 해결했지만 필자의 react setstate에 대한 이해가 다소 부족한 느낌을 받았다.