Cannot Read Property 'setstate' Of Undefined Reactjs
I am trying to set the state in React inside my function, however I get an error message stating: Cannot read property 'setState' of undefined. Below is my code, I call the state i
Solution 1:
you haven't bound the function to the class. try doing
addTimes = (id) => {
// code here
}
in the component class
Solution 2:
Try with an arrow 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);
});
} elseif(times.includes(id)){
times.remove(id)
}
console.log(times);
addTimes = () => {
this.setState({
times: times
});
}
}
Or, bind this
in addTimes
function like this :
constructor(props) {
super(props);
this.state = {
times: []
this.addTimes = this.addTimes.bind(this);
};
}
Solution 3:
better to use es6 syntax. try with below code.
classSettingsextendsReact.Component{
constructor(props) {
super(props);
this.state = {
times: []
};
let times = [];
let currentTicked = [];
this.addTimes = this.addTimes.bind(this);
}
addTimes(id) {
let 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);
});
} elseif(times.includes(id)){
times.remove(id)
}
this.setState({
times: times
});
}
render(){
this.addTimes;
return (
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);
}
}
returnthis;
}
);
}
}
Post a Comment for "Cannot Read Property 'setstate' Of Undefined Reactjs"