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

问题描述 投票:0回答:2

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

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

我有这个错误:-

意外使用'history'不受限制的全局变量

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

  window.history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
  } 
}

发现新错误:-

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

reactjs push history
2个回答
0
投票

我认为您也可以使用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 
        } 
     }
  }
}

0
投票

在您的功能组件中,您是否缺少props.history.push

© www.soinside.com 2019 - 2024. All rights reserved.