如何在Reactjs功能组件history.push中使用 [英] how to use in Reactjs functional component history.push

查看:119
本文介绍了如何在Reactjs功能组件history.push中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a functional component that has form. Onsubmit call I would like to redirect to another page.

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

我得到了这个错误:-

意外使用历史记录"无限制全局变量

Unexpected use of 'history' no-restricted-globals

在搜索错误后,我发现了类似的位置答案.答案是:尝试在位置(即window.location)之前添加窗口.所以我尝试了:-

After Googling the error I found a similar kind of answer for location. Answer was: Try adding window before location (i.e. window.location). So I tried:-

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

得到新的错误:-

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

Unhandled Rejection (TypeError): window.history.push is not a function

推荐答案

我认为您使用 react-router 处理路由.如果是这样,则需要使用通过 ReactRouterContext 传递的历史记录对象.为此,您需要使用 useHistory 钩子来获取 history 对象.

I think you handle routing with react-router. If so, you need to use the history object which is passed through the ReactRouterContext. To do that, you need to use useHistory hook to get the history object.

// ...
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 
        } 
     });
  }
}

这篇关于如何在Reactjs功能组件history.push中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆