首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在没有构建工具的情况下使用useState钩子?

如何在没有构建工具的情况下使用useState钩子?
EN

Stack Overflow用户
提问于 2021-11-09 01:46:13
回答 1查看 203关注 0票数 0

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

'Uncaught TypeError: u is undefined'

你知道为什么会这样吗?我尝试在函数组件内部和外部使用useState函数,但这两种方法都不起作用。我是不是漏掉了什么?有人能帮我指出正确的方向吗?

代码语言:javascript
复制
<!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>
EN

回答 1

Stack Overflow用户

发布于 2021-11-09 22:34:06

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

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

  1. 为每个模块使用已解析的@latest (请注意preact导入中的URL)

代码语言:javascript
复制
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

代码语言:javascript
复制
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';

这两个都应该行得通。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69891883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档