【问题标题】:I have a problem to redirect to another page in React js我在 React js 中重定向到另一个页面时遇到问题
【发布时间】:2021-12-25 05:23:21
【问题描述】:

我想在单击按钮时转到另一个页面并尝试此代码,但出现此错误 “TypeError:Cannot read properties of undefined (reading ‘push’)”

我该如何解决这个问题? 谁能帮帮我?

import { useHistory } from 'react-router-dom';

function app() {
  let history = useHistory();
  const redirect = () => {
    history.push('/pathOfMyPage ');
  }
  return (
    <div>
      <button onClick={redirect}>Click Here </button>
    </div>
  );
}

【问题讨论】:

  • 你在用 react-router v6 吗?
  • cat package.json | grep react-router
  • 你能说明你是如何使用这个功能的吗?我觉得奇怪的是它是一个小写的名字。在 JSX 中可用的 React 组件必须是大写的。

标签: reactjs


【解决方案1】:

在 react-router 6 中,如果您只运行 npm install react-router,您将获得当前版本,useHistory 似乎不再存在。看来你可以改用[useNavigate][1]

import { useNavigate } from "react-router-dom";

...

  let navigate = useNavigate();
  const redirect = () => {
    navigate("/pathOfMyPage", { replace: false });
  }

【讨论】:

  • "react-router-dom": "^5.3.0",
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 2019-03-16
相关资源
最近更新 更多