setState然后在React JS中递归地调用函数

时间:2018-10-24 09:05:18

标签: reactjs

单击按钮时,我正在逐一检查所有服务器的可用性。一旦完成第一个服务器检查,它将以++ index递归调用相同的函数。代码如下:

tempA = (index) => {
    console.log("index is--> " + index);
    let oRecord = this.state.aServers[index];
    let componentStatus = {};
    componentStatus[oRecord.id] = <div className='icon--loading'> 
</div>

    this.setState({
        componentStatus: componentStatus
    });
    var request = "component? 
operation=check_server_pingability&target_server=" + oRecord.name + 
"&_=" + getDateTime();

    fetch(request, {
        credentials: "same-origin"
    })
        .then(response => response.json())
        .then(response => {
            componentStatus[oRecord.id] = <div title= 
{response.message} className={"icon icon--" + response.status + " 
cell"}></div>
            this.setState({
                componentStatus: componentStatus
            }, () => {
                console.log(this.state.componentStatus[oRecord.id])
                this.tempA(++index);
            });
        })
   }

首先它将图标设置为加载图标。然后在网络通话后,它应该将图标更新为失败或成功。在完成第一台服务器检查之后,它应该对列表中的下一个服务器执行相同的步骤。现在的问题是,一旦完成第一台服务器检查,它将图标更新为失败,但是当它开始检查第二台服务器时,第一台服务器的状态消失并且显示空白。列表中的所有服务器都在发生这种情况。每当检查下一个服务器时,较早的服务器状态就会消失。请检查代码,让我知道问题出在哪里。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为问题出在 每次放入仅具有一个字段(let componentStatus = {};)的状态对象componentStatus时,[oRecord.id]。您应该尝试在这一行上更改此行:

let componentStatus = this.state.componentStatus;

相关问题