๐Ÿšง

[React] TypeError Cannot read property 'setState' of undefined

purpplee 2021. 12. 3. 11:26

TypeError Cannot read property 'setState' of undefined

 

class component ์—์„œ ํ•จ์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ ์•„๋ž˜์™€ ๊ฐ™์€ ํ˜•ํƒœ๋Š” ๋ช…์‹œ์ ์œผ๋กœ bind ๋ฅผ ํ•ด์ค˜์•ผ ํ•œ๋‹ค. ํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด this ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์ฐพ์„ ์ˆ˜ ์—†๋‹ค๋ฉฐ ์˜ค๋ฅ˜๊ฐ€ ๋œฌ๋‹ค.

handleClick() {
	this.setState(value);
}

 

์•„๋ž˜์ฒ˜๋Ÿผ ์ƒ์„ฑ์ž์—์„œ bind ํ•ด์ฃผ๊ฑฐ๋‚˜

constructor(props) {
	super(props);
    
    this.handleClick = this.handleClick.bind(this);
}

 

ํ•จ์ˆ˜ ์„ ์–ธ ํ˜•ํƒœ๋ฅผ arrow function ์œผ๋กœ ํ•ด์ฃผ๋ฉด ์ž๋™์œผ๋กœ bind ๋œ๋‹ค.

handleClick = (e) => {
	this.setState(value);
}
๋ฐ˜์‘ํ˜•