首页 > 解决方案 > 如何在 Preact 和没有构建工具的情况下使用 useState 钩子?

问题描述

目前,我需要让 Preact 应用程序在没有任何构建工具的情况下工作,只需使用带有 import 语句的 index.html 从 CDN 获取 preact。我可以从 CDN 导入 'useState' 钩子没有问题,甚至可以 console.log() 函数 useState 的值,但是每当我尝试使用它时,我都会收到一条错误消息:

'未捕获的类型错误:你未定义'

你会碰巧知道为什么会这样吗?我尝试在功能组件内部和外部使用 useState 函数,但无论哪种方式都不起作用。我在这里错过了什么吗?谁能帮我指出正确的方向?

<!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, Component, render } from 'https://unpkg.com/preact?module';
        import { useState } from 'https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module'
        import htm from 'https://unpkg.com/htm?module';

        // Initialize htm with Preact
        const html = htm.bind(h);
      
        const App = (props) => {

            const [testVar, setTestVar] = 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>

标签: javascriptpreact

解决方案


这是 unpkg 可以做的已知错误和限制,请参阅:https ://github.com/preactjs/preact/issues/2571

不过有几个简单的修复方法:

  1. 为每个模块使用已解析的 URL(注意@latestpreact 导入中的)
import { h, render } from 'https://unpkg.com/preact@latest?module'
import { useState } from 'https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module'
import { html } from 'https://unpkg.com/htm/preact/index.module.js?module'
  1. 使用没有此问题的 CDN 可以正确解析模块,例如skypack
import { h, render } from 'https://cdn.skypack.dev/preact';
import { useState } from 'https://cdn.skypack.dev/preact/hooks';
import { html } from 'https://cdn.skypack.dev/htm/preact';

要么应该工作。


推荐阅读