[英]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 調用?
您的變量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.