如何在 Reactjs 功能组件中使用 history.push

mas*_*boo 12 history push reactjs

我有一个具有形式的功能组件。Onsubmit 调用我想重定向到另一个页面。

function ProfileForm(props) {
 // many code removed
 const onSubmit = (data, e) => {
   e.target.reset();
   history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
   } 
  }
}
// many code removed
}
Run Code Online (Sandbox Code Playgroud)

我有这个错误:-

意外使用“历史”无限制全局变量

在谷歌搜索错误后,我找到了类似的位置答案。答案是: Try adding window before location (i.e. window.location). 所以我试过:-

  window.history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
  } 
}
Run Code Online (Sandbox Code Playgroud)

出现新错误:-

未处理的拒绝(TypeError):window.history.push 不是函数

Onu*_*der 31

我认为您使用react-router. 如果是这样,您需要使用通过ReactRouterContext. 为此,您需要使用useHistory钩子来获取history对象。

// ...
import { useHistory } from "react-router";
// ...


function ProfileForm(props) {
  const history = useHistory();
  const onSubmit = (data, e) => {
     e.target.reset();
     history.push({
        pathname:  "/OnSubmit",
        state: {
          response: messageFromServer 
        } 
     });
  }
}
Run Code Online (Sandbox Code Playgroud)