You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无构建工具的Preact项目中正确使用useState Hook?

问题修复说明

错误原因

你遇到的报错是Preact无构建场景下的高频问题,核心是引入的Preact核心包和Hooks包版本不匹配。Hooks运行时依赖同版本Preact内部的上下文实例,你的代码中核心包未指定版本、Hooks包指定了@latest,两者版本不一致时Hooks无法读取到对应的实例,就会抛出undefined错误。

修复方法

统一两个依赖包的版本即可,修正后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="module">
        // 两个包统一指定相同的版本号即可解决版本不匹配问题
        import { h, render } from 'https://unpkg.com/preact@10.19.3?module';
        import { useState } from 'https://unpkg.com/preact@10.19.3/hooks/dist/hooks.module.js?module';
        import htm from 'https://unpkg.com/htm?module';

        const html = htm.bind(h);
      
        const App = (props) => {
            const [testVar, setTestVar] = useState(0);
            // 额外提示:当前countVariable是普通变量,修改不会触发组件重渲染
            // 如果需要界面同步更新计数,可替换为 const [countVariable, setCountVariable] = useState(0)
            var countVariable = 0;

            const incrementButtonHandler = () => {
                countVariable = countVariable + 1;
            }

            const logMethod = () => {
                console.log(countVariable);
                countVariable = countVariable + 1;
            }

          return html`<div>
            <h1>Test ${props.name}!: ${countVariable}</h1>
            <button onClick=${logMethod}>Increment</button>
          </div>`;
        }
      
        render(html`<${App} name="World" />`, document.body);
      </script>
</head>
<body>
    
</body>
</html>

内容的提问来源于stack exchange,提问作者S R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:15:07