[英]how to use a for loop in ReactJS to update the state on meeting some condition? loops are not requiring to traverse from every element
我是 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>
</>
);
}
}
Output 是:右计数:1,左计数:1,因为循环没有运行,并且值仅在 function setRight 和 setLeft 中设置为 1。 map,filter方法返回一个新的数组,这里不需要。 我应该如何使 state object 计数增加?
第二个循环实际上执行了两次。 但是,您需要注意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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.