Reputation: 127
When binding this to my addTimes function I get an error stating: Cannot read property 'bind' of undefined.
I am building in ReactjJS and Webpack. I recently had another issue recent which people suggested:
this.addTimes = this.addTimes.bind(this);
See: Cannot read property 'setState' of undefined ReactJS
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
}
render(){
this.addTimes = this.addTimes.bind(this);
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var currentTicked = [];
var times =[]
function addTimes(id){
var index = times.indexOf(id);
if (!times.includes(id)) {
$("input:checkbox[name=time]:checked").each(function(){
currentTicked.push($(this).val());
times = times.concat(currentTicked)
times = jQuery.unique(times);
currentTicked = [];
});
} else if(times.includes(id)){
times = times.remove(id);
}
console.log(times);
this.setState = {
thims: times
}
}
Upvotes: 1
Views: 7598
Reputation: 112777
In order to be able to bind addTimes
to this
in the constructor, addTimes
must be a method on your class, not just a function in the render method.
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
this.addTimes = this.addTimes.bind(this);
}
addTimes(id) {
// ...
}
}
If you want to create addTimes
in the render method, you could just bind this
to the function there:
function addTimes(id) {
// ...
}.bind(this);
Or your could make it into an arrow function instead:
const addTimes = (id) => {
// ...
}
Upvotes: 5