Javascript 把钩子挂起来

Javascript 把钩子挂起来,javascript,reactjs,Javascript,Reactjs,我想为变量的初始化设置一个钩子: state = { geo: new usePosition() } 但我得到了以下错误: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching vers

我想为变量的初始化设置一个钩子:

state = { 
    geo: new usePosition()
}
但我得到了以下错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
我真的需要把这个钩子放在我的状态,以便初始化我的变量

你能帮我吗


多谢各位

你不能用这种方式。您可以做的是,在您的
组件didmount()
中,您可以尝试这样做:

state = { geo: null };
componentDidMount() {
  const geo = new usePosition();
  this.setState({ geo });
}
因此,这在
render()
函数中通过以下方式提供:

this.state.geo

还有,只是一个建议。如果您使用的是钩子,请将其与
useState()
useffect()
钩子一起用于功能组件。

为什么不在主应用程序渲染脚本中启动它?使用空值定义状态,然后在render方法(对于函数组件)中设置为new usePosition(),或者在组件的构造函数中执行此操作出于好奇,您正在类组件中使用挂钩?为什么不在带有useState钩子的功能组件中使用它们呢?嗨,Peter,欢迎来到Stack Overflow。请看,也请阅读,以便您熟悉如何使用此平台。@Alexis非常感谢!谢谢,我尝试了你的答案,但我收到了以下消息:
错误:无效的钩子调用。钩子只能在函数组件的主体内部调用。发生这种情况的原因如下:1。React和渲染器(如React DOM)2的版本可能不匹配。你可能违反了Hooks 3的规则。同一个应用程序中可能有多个React副本
Yes很遗憾:/@Peter您可以将其移动到渲染功能中吗?类似的操作:@Bob尝试了其他类似的操作。将其移动到渲染函数,如下所示: