如何在ReactJS中使用for循环来更新满足某些条件的状态?循环不需要从每个元素遍历



我是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>
</>
);
}
}

输出为:右计数:1,左计数:1因为循环没有运行,并且值仅在函数setRight和setLeft中设置为1。map,filter方法返回一个这里不需要的新数组。我应该如何使状态对象计数以在条件中递增?

第二个循环实际上执行了两次。但是,您需要注意setState是异步的。

这意味着,当您在循环中调用this.state.rightcount时,值仍然是0,因为setState尚未完成。

可以通过使用变量存储rightCountleftCount并只调用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

最新更新