目前,我需要让Preact应用程序在没有任何构建工具的情况下工作,只需使用带有导入语句的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>发布于 2021-11-09 22:34:06
这是一个已知的错误和unpkg所能做的限制,请参阅:https://github.com/preactjs/preact/issues/2571
不过,有几个简单的修复方法:
@latest (请注意preact导入中的URL)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'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';这两个都应该行得通。
https://stackoverflow.com/questions/69891883
复制相似问题