React函数组件App中使用useState触发无效Hook调用错误的解决咨询
React函数组件使用useState报错的解决办法
问题背景
我在React项目里用以下代码渲染页面:
ReactDom.render(MyClass.render(), document.getElementById('app-id'));
其中MyClass是自定义类:
import App from "./App"; class MyClass { constructor(props) { this.props = props; } render() { return App(this.props); } } window.MyClass = MyClass;
App是函数组件,原本代码正常运行,但添加useState后抛出Hook调用错误:
import { useState } from 'react'; const App = (props) => { const [ selectedStore, setSelectedStore ] = useState(store); return ( <Provider store={store} /> ); };
错误信息:
Uncaught 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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
核心原因
直接把App当作普通函数调用(App(this.props)),不是React渲染组件的正确方式。React需要亲自调用函数组件,才能建立Hook的调用上下文、追踪状态变化。这种直接调用的方式会让Hooks脱离React的管理环境,触发规则校验错误。
调整步骤
1. 修正MyClass的render逻辑
把直接调用App函数改为返回JSX组件形式,让React接管组件渲染:
import App from "./App"; class MyClass { constructor(props) { this.props = props; } render() { // 用<App />替代App(this.props) return <App {...this.props} />; } } window.MyClass = MyClass;
2. 规范页面渲染代码
当前的MyClass不是标准React组件,建议改成继承React.Component的类组件,再用JSX形式渲染:
// 改造MyClass为标准React类组件 import React from 'react'; import App from "./App"; class MyClass extends React.Component { render() { return <App {...this.props} />; } } window.MyClass = MyClass;
然后页面渲染代码更新为:
ReactDom.render(<MyClass />, document.getElementById('app-id'));
3. 简化方案:直接渲染App组件
如果MyClass没有额外业务逻辑,完全可以去掉它,直接渲染App:
import App from "./App"; ReactDom.render(<App />, document.getElementById('app-id'));
验证效果
调整后,App里的useState就能正常工作了,比如可以把状态传给Provider:
import { useState } from 'react'; import { Provider } from 'react-redux'; const App = (props) => { const [ selectedStore, setSelectedStore ] = useState(store); return ( <Provider store={selectedStore} /> ); }; export default App;
内容的提问来源于stack exchange,提问作者Glen Solsberry
相关产品推荐
相关产品推荐

