Javascript 无法读取属性';设置状态';未定义ReactJS的定义
我试图在函数内的React中设置状态,但收到一条错误消息,指出:无法读取未定义的属性“setState” 下面是我的代码,我在构造函数中调用状态,然后在addTimes函数中设置状态并将其绑定到该函数,但是仍然会出现错误Javascript 无法读取属性';设置状态';未定义ReactJS的定义,javascript,reactjs,Javascript,Reactjs,我试图在函数内的React中设置状态,但收到一条错误消息,指出:无法读取未定义的属性“setState” 下面是我的代码,我在构造函数中调用状态,然后在addTimes函数中设置状态并将其绑定到该函数,但是仍然会出现错误 class Settings extends React.Component { constructor(props) { super(props); this.state = { times: [] }; } render()
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
}
render(){
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);
});
} else if(times.includes(id)){
times.remove(id)
}
console.log(times);
addTimes = () => {
this.setState({
times: times
});
}
}
尝试使用箭头功能:
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);
});
} else if(times.includes(id)){
times.remove(id)
}
console.log(times);
addTimes = () => {
this.setState({
times: times
});
}
}
或者,在addTimes
函数中绑定this
,如下所示:
constructor(props) {
super(props);
this.state = {
times: []
this.addTimes = this.addTimes.bind(this);
};
}
最好使用es6语法。试试下面的代码
class Settings extends React.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);
});
} else if(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);
}
}
return this;
}
);
}
}
您尚未将函数绑定到类。试着做
addTimes = (id) => {
// code here
}
在组件类中这对我来说很奇怪`addTimes=()=>{this.setState({times:times});}`。为什么不直接把` this.setState({times:times})`还有,为什么要在每次渲染时在数组的原型中重新定义函数
remove
?