setState更新不及时state数据获取出现问题
因为是异步机制,所有state不会及时更新。
网上加setTime我试了下好像不怎么有用。
另外两个种的话是:
在setState回调函数内可以获得最新的数据,或者使用react的生命周期函数componentDidUpdate
可是因为特定需求这两个方法不方便使用,发现render return内更新state正常。所以使用钩子函数的方式写了几个钩子函数,可用。
return <li id={`${item.nameid}`} key={i+1} index={i+1} className={this.state.isSelect === i+1 ? `${lilight.activeted} ${lilight.cssli}` : `${lilight.cssli}`} onClick={this.setCur}>{item.name}</li>
setCur=e=>{
this.setState({
isSelect:Number(e.currentTarget.getAttribute('index'))
});
console.log(e.currentTarget.getAttribute('index'));
if (e.currentTarget.getAttribute('index')==1){
this.bianLiSite(1);
}else if (e.currentTarget.getAttribute('index')==2){
this.bianLiSite(2);
}else if (e.currentTarget.getAttribute('index')==3){
this.bianLiSite(3);
}else if (e.currentTarget.getAttribute('index')==4){
this.bianLiSite(4);
}else if (e.currentTarget.getAttribute('index')==5){
this.bianLiSite(5);
}else {
console.log("有问题"); }
}
bianLiSite=(sitePlan)=>{
console.log( this.state.site)
const aaa = [];
this.state.site.map((item,i)=>{
console.log(item)
if (item.saleplanid == sitePlan){
aaa.push(item);
}
this.setState(
{
platSite : aaa
})
});
}
记录一下。
react入门级,有什么可以改进的地方或者不对的地方欢迎大神帮忙。