我有一个具有形式的功能组件。 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不是函数
我认为您也可以使用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
}
}
}
}
在您的功能组件中,您是否缺少props.history.push
?