【问题标题】:React call from class to functional component. Error: Invalid hook call. Hooks can only be called inside of the body of a function component响应从类到功能组件的调用。错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用
【发布时间】:2022-02-03 12:50:29
【问题描述】:

我正在从类组件中调用功能组件。 这是我的功能组件,

import React, { useState, useEffect } from "react";
import {useNavigate} from "react-router";

const UtilsExt = () => {
    const navigate = useNavigate();
    navigate('/');

};

export default UtilsExt;

我从类组件的按钮单击事件中调用上面。当我这样做时,我会收到此错误。

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一:

  1. 您的 React 和渲染器版本可能不匹配(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用中拥有多个 React 副本

【问题讨论】:

    标签: reactjs react-hooks react-router


    【解决方案1】:

    React 钩子只能在函数组件或自定义 React 钩子中调用。为了使用navigate 函数,您需要创建一个包装器组件或自定义withNavigate HOC 以将navigate 作为道具传递给您的类组件。

    包装器

    const MyComponentWithNavigation = props => {
      const navigate = useNavigate();
    
      return <MyClassComponent {...props} navigate={navigate} />;
    };
    

    用法:

    <Route path="..." element={<MyComponentWithNavigation />} />
    

    HOC

    const withNavigate = Component => props => {
      const navigate = useNavigate();
    
      return <Component {...props} navigate={navigate} />;
    };
    

    用法:

    const MyComponentWithNavigation = withNavigation(MyClassComponent);
    

    ...

    <Route path="..." element={<MyComponentWithNavigation />} />
    

    访问navigate 函数

    在你的类组件中,从 props 访问navigate

    this.props.navigate("/");
    

    【讨论】:

    • 感谢您的指导。有效!一个后续问题,我们如何在新的 react-router 版本 6 中使用 url 属性(和其他属性)并将其传递给元素的组件,就像我们在 render 方法中所做的那样? react-router: V6 }/> react-router: V5
      }/>
    • @user3900196 使用相同的模式,const params = useParams(); 用于路由参数,const location = useLocation(); 等...将这些作为道具传递给组件。
    • 再次感谢。 (很抱歉在评论中提出这个问题)一个新错误:您不能在另一个 中渲染 。您的应用中不应包含多个。
    • @user3900196 正确。每个应用只需要一个路由器。
    猜你喜欢
    • 2020-07-22
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多