我剛開始反應,并試圖為客戶存盤狀態中的值,我用于獲取下拉值的代碼是這樣的:
handleChangeCC = customercode => {
this.setState({ customercode });
// var customer = customercode.map(o => o.label);
// this.setState({ customer });
var customer1 = customercode.label;
this.setState({ customer: customer1 });
console.log(`Option selected1:`, this.state.customer);
this.getCustomerName();
// console.log("Rec2:" document.getElementById("CustomerCode").innerText);
};
我在這個函式中運行函式 this.getCustomerName(),代碼是這樣的:
getCustomerName = () => {
var Items = [];
var code = this.state.customer;
console.log('CustomerCode:' code);
axios.post('https://localhost:44303/api/observation/GetCustomerName?' '&code=' code).then(response => {
//console.log('Value=' response.data);
console.log('Response=' response.data);
response.data.map(item => {
var obj = new Object();
// obj.label = desc;
obj.label = item;
Items.push(obj);
//this.setState({ locations: response.data });
});
this.setState({ customerName: Items });
console.log('customerName:' this.state.customerName);
});
};
我在函式 getCustomerName 中設定 code= this.state.customer ,我在 this.setState({ customer: customer1 }); 之后運行它。在 handleChangeCC 函式中。
然而,由于 this.setState 是一個異步函式,它不會立即更新狀態,因此我得到的代碼為 null 并且我的 getCustomerName 函式不起作用
我該如何解決這個問題?有沒有辦法將一個函式的變數值傳遞給另一個函式。請幫忙
uj5u.com熱心網友回復:
在這種情況下,我會將 傳遞customercode到您的getCustomerName()方法中。setState將需要一點時間,因此它的價值不會立即對您的方法可用。您必須等待該值處于狀態,然后呼叫該方法。通過設定其狀態并將其傳遞給您的方法,您不必等待狀態更新完成。
另外,如果你只是在學習 React,我會考慮使用基于函式的組件而不是遺留的類組件,如果你有選擇的話。
uj5u.com熱心網友回復:
是的,有幾種方法可以獲取最新值
setState 中的第二個引數
this.setState({ customerName: Items }, () => {
console.log('latest value', this.state.customerName);
});
可以選擇傳遞給 setState 的第二個引數是一個回呼函式,它在 setState 完成并重新渲染組件后立即呼叫。
更多在這里
異步方法
updateA = async () => {
this.setState({
a: "test"
});
await (() => {})(); // or fetch or any async operation
console.log(this.state.a);
};
請注意,這不是推薦的方法,但是當前版本的 react 支持它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337023.html
標籤:javascript 反应 异步等待
上一篇:Javascript:如何在界面中向字串元素添加逗號
下一篇:反應時間前沒有得到日期
