首页 > 解决方案 > 不能同时发布和重定向

问题描述

如果我注释掉作品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'
);

标签: javascriptreactjsredirect

解决方案


我不确定这是否能解决问题,但是......

在为 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


推荐阅读