我使用 reactjs 并且非常了解它,例如基礎知識。然而,我一直在研究這種奇怪的行為,一直沒能找到罪魁禍首。也許你們中的一個反應精英有一個想法,哈哈。所以我正在使用具有以下狀態物件的有狀態組件
this.state = {
buttonVisible: false,
};
所以為了顯示按鈕并改變狀態,我在承諾中這樣做
handleSubmit = async (e) => {
const { status } = this.props;
e.preventDefault();
await verifyForm().then((data) => {
const submissionSuccess = status === 'SUCCESSFUL_SUBMISSION';
this.setState({
buttonVisible: submissionSuccess
});
actions.showNotification(data);
}).catch(err => actions.showNotification(err));
};
在渲染方法中:
這是具有 onClick 處理程式的按鈕,該處理程式應將 buttonVisible 狀態設定為 true。
<Button
fullWidth
onClick={this.handleSubmit}
type="submit"
variant="contained"
color="primary">Submit
</Button>
在我使用 onClick 處理程式單擊按鈕后,如果 this.state.buttonVisible 為 true,它應該呈現以下按鈕。
{ this.state.buttonVisible &&
<Button
onClick={this.handleShowModal}
variant="contained"
color="primary">
Proceed
</Button>
}
但它沒有呈現按鈕。所以我控制臺記錄了 this.state.buttonVisible 資訊,它仍然是錯誤的。
I know that the method is not returning any error because I can see that the form is verified successfully on my end, also, it is not going to the catch block, but the .then block. I think it has something to do with the handleSubmit handler. But not sure what it is. Any help appreciated. Thanks!
uj5u.com熱心網友回復:
await回傳 Promise 的已決議值,而不是then可以附加的 Promise 。您可以修改您的代碼:
...
try{
const data = await verifyForm();
const submissionSuccess = status === 'SUCCESSFUL_SUBMISSION';
this.setState({
buttonVisible: submissionSuccess
});
actions.showNotification(data);
}catch(err){
actions.showNotification(err)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360677.html
標籤:javascript reactjs asynchronous ecmascript-6 async-await
下一篇:Vue順序執行
