javascript - 不能同时发布和重定向
问题描述
如果我注释掉作品document.location.href = 'https://www.mywebsite.ca/thankyou'
。POST
如果我取消注释,重定向有效,但POST
不会触发。
我正在使用 React,我不需要响应数据,我只需要发送(表单)数据。请帮忙,谢谢!
fetch(
"https://mycloudservice.com/myendpoint",
{
method: "POST",
body: JSON.stringify(data),
headers: { "Content-type": "application/x-www-form-urlencoded" },
}
)
.then((response) => response.json())
.then((json) => console.log('complete'))
.then(
//document.location.href = 'https://www.mywebsite.ca/thankyou'
);
解决方案
我不确定这是否能解决问题,但是......
在为 React-router 使用 browserHistory 时,最好使用以下命令来阻止浏览器刷新和您的应用重新加载。
而是试试这个:
类组件:
this.props.history.push("/path");
功能组件:
import { useHistory } from "react-router-dom";
function Foo() {
let history = useHistory();
function handleFetch() {
fetch("https://mycloudservice.com/myendpoint", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-type": "application/x-www-form-urlencoded" }
})
.then((response) => response.json())
.then((json) => console.log("complete"))
.then(()=>history.push("/path"));
}
return (
//Anything
);
}
看看这篇文章: window.location.href vs redirect utility of react-router-dom
推荐阅读
- android - 当我执行“setState”时,我在模拟器屏幕上收到此错误“Bad State: Stream has been listened”。
- single-sign-on - Keycloak 自定义属性在编辑时验证
- laravel - Laravel 8 - 根据匹配(产品,类别,页面)调用多个控制器的友好 url - 如何设计它?
- django - 如何在 django 中发布模态表单并返回到相同的模板?
- angular - Angular Universal 将 favicon.ico 视为服务器端的路由
- java - 构建功能测试时出错
- reactjs - React Router 刷新 url 但不刷新页面
- java - 使用 Spring Boot 验证 Generic Rest Api
- salesforce - 无法安装@salesforce/lwc-dev-server
- excel - 从 Microsoft CSV 读取大数据并写入 AWS 中的 Microsoft Excel 的策略