REACTJS 报错:TypeError: navigate.push 不是一个函数。

8

我试图为我的react.js网站实现一个首页。我的布局很好,代码也可以编译没有问题。

但是,当我点击按钮时,网站应用程序出现以下错误:TypeError: navigate.push不是一个函数,出错行是navigate.push("/quiz")

我对react还很陌生,如果有人能帮我,我会非常感激!

这是我的代码:

import { Button } from "@material-ui/core";
import { Container } from "@material-ui/core";
import { useNavigate } from "react-router-dom";
import "./Home.css";

const Home = () => {
  const navigate = useNavigate();

  const sendSubmit = () => {
    navigate.push("/quiz");
  };
  return (
    <Container className="content">
      <h1 id="quiz-title">Phishing Quiz</h1>
      <h2 class="question-text">
        Do you think you can beat our phishing quiz?
      </h2>
      <p className="description">
        {" "}
        There are many social engineering attacks on internet however not all of
        them are good enough to trick users. However there are some scams that
        are identical to original websites and usually most of the users get
        tricked by them.
      </p>
      <p className="description">
        Do you think you are smart enough to handle these attacks?
      </p>
      <p className="description">
        We are challenging you with our phishing quiz which will show you
        examples of really good social engineering attacks on internet. We hope
        you can pass!
      </p>
      <p>""</p>
      <Button
        className="button"
        variant="contained"
        color="primary"
        size="large"
        onClick={sendSubmit}
      >
        Start Quiz
      </Button>
    </Container>
  );
};

export default Home;


使用的是哪个版本的react-router-dom?如果是v5,您可以使用import { useHistory } from "react-router-dom";代替useNavigate。 - Mahesh K S
@Mahesh 当我尝试使用 useHistory 时,会出现以下错误:Attempted import error: 'useHistory' is not exported from 'react-router-dom'. 此外,我的版本是 6.0.2 ,即 react-router-dom@6.0.2 - babybirkins
1
在v6中,useHistory被useNavigate替换了,因此您可以使用以下代码进行检查:import {useNavigate} from 'react-router-dom'; const navigate = useNavigate(); navigate('/quiz'); - Mahesh K S
@Mahesh 我可以在 onClick={} 中调用 navigate('/home') 吗? - babybirkins
2
你可以使用 navigate("/quiz") 代替 navigate.push("/quiz")。 - Mahesh K S
@Mahesh 运作得非常好!非常感谢你!如果你能将你的代码提交为答案,我就可以将其标记为解决方案 :) - babybirkins
2个回答

7

可以使用以下代码进行检查

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

在 Home 箭头函数内部

const navigate = useNavigate();

const sendSubmit = () => {
    navigate("/quiz");
};

这对我解决了问题,但我不明白为什么很难找到这个信息,即必须使用navigate(...)而不是navigate.push(...)。无论如何,谢谢。 - Edvin Keskin

1
发布推送时,您的代码必须如下所示:
const Home = () => {
const navigate = useNavigate();

// delete push
const sendSubmit = () => {
navigate("/quiz");
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接