how to use in Reactjs functional component history.push

我与影子孤独终老i 提交于 2021-02-08 12:59:15

问题


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
}

I got this erro:-

Unexpected use of 'history' no-restricted-globals

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 
  } 
}

got new error:-

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


回答1:


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



回答2:


If you are using import { withRouter } from "react-router-dom"; In your functional component, aren't you missing props.history.push?



来源:https://stackoverflow.com/questions/60516300/how-to-use-in-reactjs-functional-component-history-push

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!