เมื่อเริ่มเขียน React components อาจเจอ error: Cannot read property 'setState' of undefined และ this.setState is not a function บทความนี้เสนอวิธีแก้ 2 วิธี
สาเหตุ
Error เกิดเพราะ method ใน React Component ไม่ได้ bind this ถูกต้อง
โค้ดที่ทำให้ Error
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { input: "" };
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value}); // this ไม่ได้ bind
}
render() {
return (
<div className="App">
<input name="input" onChange={this.handleChange} value={this.state.input} />
</div>
);
}
}
ดูปกติแตกต่างจริงๆ handleChange ไม่ได้ bind กับ class App ดังนั้น this จะชี้ไปที่ Window object ไม่ใช่ App component
วิธีแก้ 2 วิธี
1. Bind ใน Constructor
ใน constructor หลัง state เพิ่ม:
this.handleChange = this.handleChange.bind(this);
ทำให้ this ใน handleChange ชี้ไปที่ App component ตลอด
2. ใช้ ES6 Arrow Function
Arrow function bind this อัตโนมัติ ไม่ต้อง bind ใน constructor:
handleChange = (e) => {
this.setState({[e.target.name]: e.target.value});
}
สรุป
ทั้ง 2 วิธีแก้ error this.setState is undefined/not a function ใน class components ได้ หากต้องการหลีกเลี่ยง error เหล่านี้ในอนาคต แนะนำ refactor เป็น functional components ใช้ React Hooks แทน!