【问题标题】:useNavigate() breaks the hookuseNavigate() 打破了钩子
【发布时间】:2022-12-05 00:35:26
【问题描述】:

我做了一个简单的反应钩子。

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

export default function SearchReq(searchTerm: string) {
  if (searchTerm === "") return;
  const navigate = useNavigate();
  console.log(searchTerm);
  // window.location.href = "/search?searchTerm=" + searchTerm;
  navigate("/search?searchTerm=" + searchTerm, { replace: true });
}

但出于某种原因,它给了我一个错误,我发现导致错误的行是const navigate = useNavigate(),但我不明白为什么有人能向我解释一下?

这是错误:

【问题讨论】:

  • “断钩”是什么意思?
  • 哦,抱歉,我知道我忘记了什么,我已经对错误进行了更新。

标签: reactjs typescript


【解决方案1】:

在组件的根级别定义挂钩。返回声明之前

export default function SearchReq(searchTerm: string) {

  const navigate = useNavigate();  

  // window.location.href = "/search?searchTerm=" + searchTerm;

  useEffect(() => {
        if(searchTerm)  navigate("/search?searchTerm=" + searchTerm, { replace: true });

  }, [searchTerm])

  return null
}

【讨论】:

  • 我已经尝试过了,但没有修复错误,但谢谢。
  • 尝试围绕 useEffect 移动导航
  • 还在组件末尾添加一个return语句
  • 是的,我做了所有这些,但没有任何帮助。
  • 您是否尝试过删除 if 条件并在 useEffect 中处理它。查看更新
【解决方案2】:

要使用 useNavigate 挂钩,您需要确保您的 React 组件在 react-router 库中的 Router 组件内呈现。

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

function MyComponent() {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate("/some/other/route");
  };

  return (
    <button onClick={handleClick}>
      Go to some other route
    </button>
  );
}

function App() {
  return (
    <Router>
      <MyComponent />
    </Router>
  );
}

要求编辑:

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

function MyComponent() {
  const navigate = useNavigate();

  // Navigate to a different route when the button is clicked
  const handleClick = () => {
    navigate("/some/other/route");
  };

  return (
    <button onClick={handleClick}>
      Go to some other route
    </button>
  );
}

【讨论】:

  • 哦好的,谢谢你说我只是想做一个函数,当触发时会重定向我所以看起来我需要找到另一种方法但谢谢你。
  • 我为此进行了编辑,再次检查帖子。
  • 谢谢,但这不完全是我的意思,您仍在输出一个按钮,并且我有一个调用此函数的表单,所以我正在考虑在提交表单时使用Navigate
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
相关资源
最近更新 更多