将钩子置于一种状态



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

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

我真的需要把这个钩子放在我的状态中,以便初始化我的变量。。。

你能帮我吗?

非常感谢!

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

state = { geo: null };
componentDidMount() {
const geo = new usePosition();
this.setState({ geo });
}

因此,这可在render()函数中通过以下方式获得:

this.state.geo

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

最新更新