gpt4 book ai didi

reactjs - 如何在 Reactjs 功能组件中使用 history.push

转载 作者:行者123 更新时间:2023-12-03 15:22:56 24 4
gpt4 key购买 nike

我有一个具有形式的功能组件。 Onsubmit 调用我想重定向到另一个页面。

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



在谷歌搜索错误后,我找到了类似的位置答案。答案是: Try adding window before location (i.e. window.location).所以我试过:-
  window.history.push({
pathname: "/OnSubmit",
state: {
response: messageFromServer
}
}

出现新错误:-

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

最佳答案

我认为您使用 react-router 处理路由.如果是这样,您需要使用通过 ReactRouterContext 传递的历史对象。 .
为此,您需要使用 useHistory Hook 获取 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
}
});
}
}

关于reactjs - 如何在 Reactjs 功能组件中使用 history.push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60516300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com