【发布时间】:2020-08-03 09:19:12
【问题描述】:
我有一个我想用 axios 调用的数据数组,我没有使用 axios.all 因为我想知道每个请求的进度,并且使用 axios.all 方法是在所有请求完成后调用,我想要显示剩余 15/50 个请求之类的内容。
for 循环内的请求有效,但调用 setState 只呈现一次,我知道 setState 是异步的,由于性能问题,我认为 React 没有多次调用 setState。
我真正的问题是更新 for 循环内的 react 状态并更新 JSX。
这是 for 循环问题的 CodeSandbox:https://codesandbox.io/s/frosty-field-mdodx?file=/src/App.js:0-597
这里是上传方法的要点和我提出请求的方式:
uploadRecords = async () => {
const { recordsUpdated } = this.state
const { recordData } = this.props
for (const record of recordData) {
const response = await createRecord(tenant) //Method of axios
this.setState({ recordsUpdated: [...recordsUpdated, response] })
}}
这是 JSX:
<div>
<p className="alert-description text-center">
Please wait and do not leave the page while we upload the records
</p>
<p className="alert-description text-center">
Uploading: {recordsUpdated.length}/{totalRecords}
</p>
<div className="progress-container">
<p className="text-muted">{recordsUpdated.length}%</p>
<Progress color="info" value={recordsUpdated.length} />
</div>
</div>
所有记录都上传没有问题,但状态只显示1更新。
感谢所有反馈和不同的方法
【问题讨论】:
-
您可能正在使用旧状态更新状态。尝试
this.setState((currentState)=>{recordsUpdated: [...currentState.recordsUpdated, response]}方法,它使用更新发生时的状态,不太可能用旧状态覆盖状态。 -
在您共享的沙箱代码中,您尚未在构造函数中定义宽度状态,并且永远不会初始化 for 循环。修复这些将使您的代码正常工作
-
@KaranSingh 是的,我的错误修复没有像我预期的那样工作。
-
像你建议的那样更新状态@GarrettMotzner 解决它!谢谢!
标签: javascript reactjs for-loop setstate