[英]How to redirect to another page and display flash message in Nextjs
我正在處理 Reactjs 和 nextjs,現在我正在通過 axios(Api) 提交表單 表單提交成功但在提交表單后我希望頁面應該更改(應該顯示 Allblogs.js,類似於重定向)並顯示 flash 消息“你的表單提交成功”怎么辦? 這是我當前的代碼
const response = await axios({
method: "post",
url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
alert('Form submitting successfully');
//should redirect and display flash messag on another page
}).catch(function (error) {
alert('respone is '+ error);
});
您可以使用查詢推送新路徑,並在新頁面中查看查詢是否存在,以便顯示警報
const router = useRouter();
const response = await axios({
method: "post",
url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
router.push({ pathname: "/home", query: { form: "submited" } });
})
.catch(function (error) {
alert('respone is '+ error);
});
並在主頁中:
const router = useRouter();
useEffect(() => {
if(router.query?.form === 'submited')
{
alert('Form submitting successfully');
router.replace('/home', undefined, { shallow: true });
}
}, [router.query]);
如果您要將數據發布到外部站點並希望重定向回您的站點,您可以只添加一個“then”並重定向。
const router = useRouter();
const response = await axios({
method: "post",
url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
alert('Form submitting successfully');
//should redirect and display flash messag on another page
}).then(() => router.push('/home'))
.catch(function (error) {
alert('respone is '+ error);
});
如果這是用於內部鏈接,則可以使用forms 和 API 路由。
const response = await axios({
method: "post",
url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
alert('Form submitting successfully');
//should redirect and display flash messag on another page
navigate("/");
alert("Your flashing message will be displayed on your rendered page")
}).catch(function (error) {
alert('respone is '+ error);
});
我在說這個。 嘗試在你的韓元上執行你希望它如何閃爍你的消息的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.