问题描述
我有一个具有形式的功能组件.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
}
我得到了这个错误:-
在搜索错误后,我发现了类似的位置答案.答案是:尝试在位置(即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
}
}
得到新的错误:-
推荐答案
我认为您使用 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中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!