简体   繁体   中英

why my React setstate is not updating immediately?

This a my function

    onSelectAction = (x, o) => {
    var { takeActionsOptions } = this.props.main
    console.log(o, "onSelectAction")
    var tempAction=_.cloneDeep(takeActionsOptions)

    _.keys(tempAction).map(a => {
        if(a === x.processCode) {
            tempAction[a].map((b)=>{
                b.isSelected = b.id === o.id

            })
        }
        else{
            tempAction[a].map((b)=>{
                b.isSelected = b.id === 0
            })
        }
    })
    StoreActions.setState({ takeActionsOptions:tempAction});
    this.onClickTakeAction(o, x)
}

where tempAction is changing the property like the i wanted to. But when im trying update the store... this { takeActionsOptions:tempAction} is not getting updated for the first time. After 2-3 clicks on the desired location this is getting updated. i want to update immediately in the store because there is another function which fetches data from the store and does another operation.

this is my other function which is using the take "takeActionsOptions " from store. so if that function is not updating then this function isnt working properly

    onClickTakeAction = (o, x) => {
    var { takeActionsOptions=[] } = this.props.main
    var selectedAction = takeActionsOptions[x.processCode].find(a => a.isSelected)
    if (selectedAction.id === 0) {
        hydro.msg.info("Please select an option.")
        return;
    }
    var tempAction=_.cloneDeep(takeActionsOptions)
    _.keys(tempAction).map(a => {
        tempAction[a].map((b)=>{
            b.isSelected = b.id === 0
        })
    })
    this.setState({takeActionsOptions:tempAction})

    switch (selectedAction.id) {
        case 1:
            var userName = somecode.userName;
            if (userName.toUpperCase() === x.userName.toUpperCase()) {
                Actions.deleteSelectedProcess(x);
            }
            else {
                somecode.info("Not your Process")
            }
            break;
        case 2:
            Action.downloadLogs(x);
            break;
       
    }
}
var tempAction=_.cloneDeep(takeActionsOptions)

What the cloneDeep function is doing here? If it does any API calling/Getting data from the server, you need to wait for a moment to get the data. Meanwhile, you can disable the button and show some loaders for interactivity.

If you're using the loadash to deep copy the object, up to my knowledge loadash functions, takes a long time to complete based on the CPU or object you are trying to copy. So try to wait for a minute and check whether it's updating or not. If it is updating, then you should disable the button until then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM