我正在尝试增加我的状态变量,但每当我这样做时都会弹出一个错误,提示变量状态未定义。 我在构造函数中定义了我的变量。显然 setState 函数中发生了某些事情。
这是呈现错误的代码:
displayDiv(){
var arr=[];
if (this.state.flag[2]){
this.setState({counter:counter+4}); // error:undefined
for (let i = this.state.counter-4; i < this.state.counter; i++)
arr.push(this.state.arrayHeader[0].content);
}
}
return(
arr.map(function(item,i){
return (
<div className="bodydiv col-sm-3">
<Header/>
<Content/>
<Tags/>
</div>
);
})
);
}
这是构造函数中定义的变量:
constructor(props){
super(props);
this.state = {
arrayHeader:[],
arraytag1:[],
arraytag2:[],
counter:0,
flag:[false,false,false]
}
}
最佳答案
您的计数器 +4
没有指向任何地方。
应该是this.state.counter + 4
此外,如果您在 render()
上调用此函数,请确保它之前已绑定(bind),您可以在构造函数上这样做:
this.displayDiv = this.displayDiv.bind(this);
关于javascript - this.setState 使变量未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093109/