请查看以下代码中elfe-if
条件内的validate方法。我无法调用useLocation
的{{1}}方法。我在网上看到了一些问题,其中一个与此类似:Invalid hook call。但是该解决方案建议从类更改为函数。这可能不是我的解决方案,因为我在表单验证期间使用类的实例来查找值。
react-router-dom
答案 0 :(得分:0)
useLocation
是custom 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将路由器上下文作为道具match
,location
和history
注入到您的组件中。
答案 1 :(得分:0)
在类组件中不支持钩子。如果您不能轻易地将其重写为功能组件,则一种选择是将类组件包装为功能组件,然后将location
作为道具传递。看来您只在使用params.pathname
,所以您可以将其传递进来。
类似这样的内容(组件名称仅是一个建议):
Reset
重命名为ResetBody
interface IResetProps extends IFormProps {
adminID : string;
}
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} />
}