问题
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