reactjs - 基于方法链中的多个 setStates() 重新渲染组件的策略?
问题描述
在我的 componentDidMount() 中,我需要调用多个专门的方法。这些方法中的每一个都需要在方法结束时调用 setState。有没有办法以某种方式推迟 this.setState 执行组件重新渲染,直到所有方法都完成?这是一些伪代码,希望能说明我所想的一般概念:
componentDidMount(){
this.setState.disableRerender();
this.DoOneThing();
this.DoSomethingElse();
this.setState.enableRerender();
}
DoOneThing(){
//this.setState(...)
}
DoSomethingElse(){
//this.setState(...)
}
解决方案
你可以用async/await
做你想做的事,然后setState
用结果:
async componentDidMount(){
const firstThing = await this.DoOneThing();
const secondThing = await this.DoSomethingElse();
this.setState({firstThing, secondThing})
}
DoOneThing(){
return new Promise((res, rej) => {
// do the first thing
res(5)
})
}
DoSomethingElse(){
return new Promise((res, rej) => {
// do the other thing
res(10)
})
}
推荐阅读
- r - 如何在嵌套列表中执行条件搜索
- angular - 如何从 mat-select 中获取取消选择的值
- regex - 正则表达式 - 匹配字符但不匹配正斜杠
- javascript - Object.prototype 不支持选项 [方法名称]
- swift - 使用 URLSession 将数据获取到 PHP 方法 - swift
- flutter - 从图库中选择后颤振设置图像
- ios - 使用photooutput抓图,图片大小随机变化
- java - 为什么 String、StringBuffer 和 StringBuilder 类使用字节数组而不是字符数组来存储字符串的字符?
- c# - 发布 ASP.NET 核心时 Serilog 不记录
- sql - 如何仅替换搜索字符串后的下一个单词?