我是React的新手,无法使用for循环。如果满足条件,则forloop增加计数。下面是我的代码:
class CountWalls extends React.Component{
constructor(props){
super(props);
this.state = {
leftcount : 0,
rightcount : 0
}
}
componentDidMount(){
const arr = [4, 1, 1, 3, 2];
let max = 0;
max = Math.max(...arr);
if(arr[0] <= max){ this.setleft() }
if(arr[arr.length - 1] <= max){ this.setright() }
for(var i = 1; i < arr.length; i++){
if(arr[0] == max) break;
if(arr[i]<=max && arr[i] > arr[i-1]){
this.setState({leftcount: this.state.leftcount + 1});
}
}
for(var i = arr.length-2; i >=0; i--){
if(arr[arr.length-1]==max) break;
if(arr[i]<= max && arr[i] > arr[i+1]){
this.setState({rightcount: this.state.rightcount + 1});
}
}
}
setright = () =>{
this.setState({rightcount: 1});
}
setleft = () =>{
this.setState({leftcount: 1});
}
render(){
return(
<>
<h2>Right count: {this.state.rightcount}</h2>
<h2>Left count: {this.state.leftcount}</h2>
</>
);
}
}
输出为:Right count:1,Left Count:1,因为循环没有运行,并且值仅在函数setRight和setLeft中设置为1。map,filter方法返回一个新数组,这里不需要。如何使状态对象计数增加条件?
第二个循环实际上执行两次。但是,您需要意识到这setState
是异步的。
这意味着当您在this.state.rightcount
循环内调用时,该值仍然0
是因为setState
尚未完成。
您可以使用变量存储rightCount
和leftCount
并仅调用setState
一次来解决此问题。
class CountWalls extends React.Component{
constructor(props){
super(props);
this.state = {
leftcount : 0,
rightcount : 0
}
}
componentDidMount(){
const arr = [4, 1, 1, 3, 2];
let max = Math.max(...arr);
let leftCount = 0;
let rightCount = 0;
if(arr[0] <= max){ leftCount = 1; }
if(arr[arr.length - 1] <= max){ rightCount = 1; }
for(let i = 1; i < arr.length; i++){
if(arr[0] === max) break;
if(arr[i]<=max && arr[i] > arr[i-1]){
leftCount++;
}
}
for(let i = arr.length-2; i >=0; i--){
if(arr[arr.length-1] === max) break;
if(arr[i]<= max && arr[i] > arr[i+1]){
rightCount++;
}
}
this.setState({
rightcount: rightCount,
leftcount: leftCount,
});
}
render(){
return(
<>
<h2>Right count: {this.state.rightcount}</h2>
<h2>Left count: {this.state.leftcount}</h2>
</>
);
}
}
您可以在此处了解更多信息:https : //medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句