![](/img/trans.png)
[英]Confirmation modal connecting to redux store using mapStateToProps gives an ERROR
[英]Make a Confirmation Modal using React & Redux
我正在制作一個應用程序,我需要在其中制作一個確認框來詢問用戶是否要刪除記錄。 我想在全球范圍內使用確認框。
假設我要刪除一條記錄,當用戶點擊刪除按鈕時,它會執行刪除記錄的操作。 但是一旦進入刪除操作,就會調度另一個操作來顯示模態。 (直到這一點我已經達到)
但是,我在執行應該等待用戶單擊確認或取消的部分上苦苦掙扎。 一旦用戶執行了操作,刪除記錄的執行就應該繼續。
我希望我的問題陳述很清楚。
請讓我知道我該怎么做。 我真的很想了解這個東西在 React 中是如何工作的。
目前,我正在使用窗口確認詢問用戶是或否。
// Delete Profile
export const deleteProfile = (history) => async (dispatch) => {
try {
if (
window.confirm('Are you Sure? Your account would be permanently lost')
) {
await axios.delete(`/api/profile`);
dispatch({ type: actionTypes.CLEAR_PROFILE });
dispatch({ type: actionTypes.ACCOUNT_DELETED });
history.push('/login');
dispatch(
setAlert('Your account has been deleted permanently', 'success')
);
}
} catch (err) {
dispatch(setAlert('Profile deletion error', 'danger'));
}
};
我希望調用一個模式來代替 window 確認並等待用戶輸入,如果它返回 true 我想繼續前進或者中止。
您必須創建一個名為 Dialog 的組件,它會在調用 deleteProfile 方法時打開,並放置兩個按鈕,一個用於取消,另一個用於刪除,當按下刪除按鈕時,您將調用刪除代碼。 我建議你使用像material-ui這樣的庫。 該庫有多個有用且非常漂亮的組件供您使用。 對於這種情況,我特別推薦您使用Dialog組件。 你可以像這樣使用它:
<Dialog
open={dialogOpen}
onClose={dialogClose}
>
<DialogContent>
Are you Sure? Your account would be permanently lost
</DialogContent>
<DialogActions>
<Button>Cancel</Button>
<Button onClick={deleteMethod}>Delete</Button>
</DialogActions>
</Dialog>
其中dialogOpen
是 boolean 組件 state 或 redux state 為真時,對話框將打開; dialogClose
是一種方法,您可以在其中將dialogOpen
state 更改為 false 以關閉對話框。
現在你可以檢查你有deleteMethod
,所有你刪除的代碼都將在其中。 按下刪除按鈕時調用此代碼。
要異步打開對話框,您可以在設置dialogOpen
變量后放置並等待,如下所示:
await this.setState({dialogOpen: true});
或者如果你想要一個像這樣的異步方法:
const method = async () =>{
await this.setState({dialogOpen: true});
}
你只需要像這樣調用方法:
await method();
我希望這有幫助!
單擊刪除按鈕打開確認框。 單擊確認按鈕刪除記錄。
謝謝。 我試過了,它真的很管用。 我怎么沒想到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.