【问题标题】:How to use useState hook with Preact and no build tools?如何在 Preact 和没有构建工具的情况下使用 useState 钩子?
【发布时间】:2021-11-09 01:46:12
【问题描述】:

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

'Uncaught TypeError: u is undefined'

你会碰巧知道为什么会这样吗?我尝试在功能组件内部和外部使用 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>

【问题讨论】:

    标签: javascript preact


    【解决方案1】:

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

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

    1. 为每个模块使用已解析的 URL(注意 preact 导入中的 @latest
    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';
    

    两者都应该工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 2023-02-24
      • 1970-01-01
      • 2015-09-22
      相关资源
      最近更新 更多