簡體   English   中英

如何在 ReactJS function 中獲取最新的 state 值?

[英]How to get latest state value in ReactJS function?

function下面根據情況從2-3個地方調用。 我正在根據我的 state 中的值進行 api 調用,如下所示:

myFunction = () => {
    # do something
    const { myVariable } = this.state;
    if (!myVariable.item) {    // myVariable.item is not getting latest variable
        makeAPICall().then(data => {
            myVariable.item = data;
            this.setState({ myVariable });    // setting in state here
        });
    }
}

一次調用上述 function 后,state myVariable應該設置為 item,但是當它再次調用時, myVariable.item未定義。

我該怎么做才能從我的 state 中獲取最新值,以防止另一個 api 調用?

問題:State 突變

您的變量myVariable是 object 對 this.state.myVariable 中的this.state.myVariable的引用。 您不能像myVariable.item = data那樣分配給它,因為這是 state 的非法突變。

解決方案

您需要創建一個新的 object,您可以使用 object 擴展語法來完成。

myFunction = () => {
    const { myVariable } = this.state;
    if (!myVariable.item) {
        makeAPICall().then(data => {
            this.setState({ 
               myVariable: {
                  ...myVariable, // copy all properties
                  item: data, // override item property
               }
            });
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM