首页 > 解决方案 > 反应钩子是否通过 CDN 链接在一个简单的单个 html 文件中工作?

问题描述

下面的html&js有什么问题,我不能用钩子!...这是我项目中唯一的文件(没有其他文件或包管理器)

<html>
<body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin ></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin ></script>
    <script>
        function Component() {
            React.useEffect(() => console.log('Hooks are working!!'))
            return React.createElement('h1', null, 'Hello World')
        }
        ReactDOM.render(Component(), document.getElementById('root'))
    </script>
</body>
</html>

我在浏览器控制台中收到以下错误(您可以通过将 html 复制到index.html文件中并双击它来重现它):

react.development.js:1501 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:
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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1501)
    at Object.useEffect (react.development.js:1544)
    at Component (index.html:8)
    at index.html:11
resolveDispatcher   @   react.development.js:1501
useEffect   @   react.development.js:1544
Component   @   index.html:8
(anonymous) @   index.html:11

如果我注释掉React.useEffect(() => console.log('Hooks are working!!'))它可以工作......但没有反应钩子:(

标签: javascriptreactjsreact-hooks

解决方案


React.createElement不仅需要用于 . h1,还需要用于整个容器 - Component. 这样Component()做不会让 React 将其与普通函数调用区分开来(因此不允许内部的钩子调用) -Component改为传递createElement

<div id="root"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin ></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin ></script>
<script>
    function Component() {
        React.useEffect(() => console.log('Hooks are working!!'))
        return React.createElement('h1', null, 'Hello World')
    }
    ReactDOM.render(React.createElement(Component), document.getElementById('root'))
</script>


推荐阅读