无效的挂钩调用。挂钩只能在功能组件的主体内部调用

时间:2020-10-26 11:27:14

标签: reactjs typescript ionic-framework ionic-react

请查看以下代码中elfe-if条件内的validate方法。我无法调用useLocation的{​​{1}}方法。我在网上看到了一些问题,其中一个与此类似:Invalid hook call。但是该解决方案建议从类更改为函数。这可能不是我的解决方案,因为我在表单验证期间使用类的实例来查找值。

react-router-dom

2 个答案:

答案 0 :(得分:0)

useLocationcustom react hook,并且只能在function component内部使用,即定义为javascript函数的组件。您的组件是一个类组件。

要访问路由器上下文在类组件中提供的location对象,可以使用withRouter HOC:

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

HOC将路由器上下文作为道具matchlocationhistory注入到您的组件中。

答案 1 :(得分:0)

在类组件中不支持钩子。如果您不能轻易地将其重写为功能组件,则一种选择是将类组件包装为功能组件,然后将location作为道具传递。看来您只在使用params.pathname,所以您可以将其传递进来。

类似这样的内容(组件名称仅是一个建议):

  1. Reset重命名为ResetBody
  2. 通过扩展为道具创建新类型。

interface IResetProps extends IFormProps {
    adminID : string;
}
  1. 创建一个名为Reset的新组件,如下所示:
function Reset(props : IFormProps){
    const params = useLocation();  //<------ unable to call this  ------------
    const adminID = params.pathname.substr(params.pathname.lastIndexOf('/')+1);

    return <ResetBody {...props} adminID={adminID} />
}