রিয়্যাক্ট কম্পোনেন্ট লিখতে শুরু করার সময় Cannot read property 'setState' of undefined বা this.setState is not a function এরর দেখা যেতে পারে। এর কারণ হলো মেথড সঠিকভাবে বাইন্ড (bind) না করা।
কারণ
ক্লাস কম্পোনেন্টে মেথড (যেমন handleChange) ক্লাসের সাথে বাইন্ড না থাকলে this উইন্ডো অবজেক্টকে রেফার করে।
দুইটি সমাধান
১. কনস্ট্রাক্টরে বাইন্ড করা
constructor(props) {
super(props);
this.state = { input: "" };
this.handleChange = this.handleChange.bind(this); // বাইন্ড
}
২. ES6 অ্যারো ফাংশন ব্যবহার করা
handleChange = (e) => {
this.setState({[e.target.name]: e.target.value});
}
অ্যারো ফাংশন অটোমেটিক্যালি this বাইন্ড করে দেয়। ভবিষ্যতে এই এরর এড়াতে ফাংশনাল কম্পোনেন্ট এবং React Hooks ব্যবহার করুন।